master
ブランチ master
LittleBeast / src / Std / Lib / Fedi / Inbox.php
16.3 KB、360行 生 Blame 履歴
1<?php
2/*************************************************************
3# 076 License
4
5Copyright (c) テクニカル諏訪子
6
7Permission is hereby granted to any person obtaining a copy of the software
8Little Beast (the "Software") to use, modify, merge, copy, publish, distribute,
9sublicense, and/or sell copies of the Software, subject to the following conditions:
10
11 1. **Origin Attribution**:
12 - You must not misrepresent the origin of the Software; you must not claim
13 you created the original Software.
14 - If the Software is used in a product, you must either:
15 a. Provide clear attribution in the product's documentation, user interface,
16 or other visible areas, **OR**
17 b. Pay the original developers a fee they specify in writing.
18 2. **Usage Restriction**:
19 - The Software, or any derivative works, dependencies, or libraries
20 incorporating it, must not be used for censorship or to suppress freedom of
21 speech, expression, or creativity. Prohibited uses include, but are not
22 limited to:
23 - Censorship of so-called "hate speech", visuals, non-mainstream opinions,
24 ideas, or objective reality.
25 - Tools or systems designed to restrict access to information or
26 artistic works.
27 3. **Notice Preservation**:
28 - This license and the above copyright notice must remain intact in all copies
29 of the source code.
30
31THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
32INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
33PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
34HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
35CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
36OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 */
38namespace Std\Lib\Fedi;
39
40use Std\Lib\Activitypub;
41
42/**
43 * 受付ボックス(共有の/ap/inboxとユーザー毎の/ap/users/{名前}/inbox)に届いたアクティビティの処理
44 *
45 * 署名の検証は呼ぶ側(Fediverseコントローラー)で行う。
46 * ローカルのユーザーからのアクティビティ(Delivery::enqueue)も、HTTPを使わずにここで処理する。
47 */
48final class Inbox {
49 /**
50 * アクティビティを処理する
51 *
52 * @param array $activity アクティビティ(署名検証済み)
53 * @param bool $local このサイトのユーザーからか
54 * @return array [HTTPステータス, レスポンスの本文]
55 */
56 public static function handle(array $activity, bool $local = false): array {
57 $actor = Fedi::id($activity['actor'] ?? null);
58 $type = (string)($activity['type'] ?? '');
59 if ($actor === null) return [400, ['error' => 'actorがありません']];
60 // ローカルのアクターを名乗るリモートのアクティビティは受け付けない
61 if (!$local && Fedi::isLocal($actor)) return [403, ['error' => '不正なactor']];
62 if (Actor::isDomainBlocked($actor)) return [403, ['error' => 'ブロックされています']];
63
64 try {
65 return match ($type) {
66 'Follow' => self::follow($activity, $actor),
67 'Accept' => self::accept($activity, $actor, true),
68 'Reject' => self::accept($activity, $actor, false),
69 'Undo' => self::undo($activity, $actor),
70 'Create' => self::create($activity, $actor, $local),
71 'Update' => self::update($activity, $actor),
72 'Delete' => self::delete($activity, $actor),
73 'Like' => self::like($activity, $actor),
74 'Announce' => self::announce($activity, $actor, $local),
75 'Block' => self::block($activity, $actor),
76 'Flag' => self::flag($activity, $actor),
77 default => [202, ['status' => '未対応なアクティビティタイプ: '.$type]],
78 };
79 } catch (\Throwable $e) {
80 logger(\LogType::ActivityPub, "受付ボックスの処理に失敗({$type}):".$e->getMessage());
81 return [500, ['error' => '処理に失敗']];
82 }
83 }
84
85 //////
86
87 private static function follow(array $a, string $actor): array {
88 $target = Fedi::id($a['object'] ?? null);
89 if ($target === Fedi::blogActorUrl()) return (new Activitypub())->handleInbox($a);
90 $username = $target ? Fedi::localUsername($target) : null;
91 if ($username === null || Fedi::localActor($username) === null) return [404, ['error' => 'アカウントが見つかりません']];
92
93 if (Actor::isBlocked($username, $actor)) {
94 Social::rejectFollow($username, $a);
95 return [202, ['status' => '拒否しました']];
96 }
97 if (Actor::isFollowedBy($username, $actor)) {
98 // 既にフォロワー:もう一度Acceptを返す(相手が状態を失った場合)
99 Social::acceptFollow($username, $a);
100 return [202, ['status' => 'OK']];
101 }
102 if (Actor::settings($username)['locked']) {
103 Fedi::update(Fedi::userPath($username, 'requests.json'), fn($l) => [$actor => ['activity' => $a, 'at' => time()]] + $l);
104 Actor::notify($username, 'follow_request', $actor);
105 return [202, ['status' => '承認待ち']];
106 }
107 Social::acceptFollow($username, $a);
108 return [202, ['status' => 'OK']];
109 }
110
111 /**
112 * 自分が送ったFollowへのAccept・Reject
113 * Rejectはフォロワーを外された場合(Followが自分の場合)もある
114 */
115 private static function accept(array $a, string $actor, bool $accepted): array {
116 $obj = $a['object'] ?? null;
117 $followId = Fedi::id($obj);
118 $follower = is_array($obj) ? Fedi::id($obj['actor'] ?? null) : null;
119
120 foreach (Social::localUsernames() as $u) {
121 $me = Fedi::actorUrl($u);
122 $f = Actor::following($u)[$actor] ?? null;
123 if ($f === null) continue;
124 if ($follower !== null && $follower !== $me) continue;
125 if ($follower === null && $followId !== $f['id']) continue;
126 Fedi::update(Fedi::userPath($u, 'following.json'), function($l) use ($actor, $accepted) {
127 if ($accepted) $l[$actor]['state'] = 'accepted';
128 else unset($l[$actor]);
129 return $l;
130 });
131 // 相手の最近の投稿をホームに入れる(取得はcronで。ここで待たせると相手のサーバーが再送する)
132 if ($accepted) Delivery::queueBackfill($actor);
133 }
134 return [202, ['status' => 'OK']];
135 }
136
137 private static function undo(array $a, string $actor): array {
138 $inner = $a['object'] ?? null;
139 if (is_string($inner)) $inner = self::findOwnActivity($inner, $actor);
140 if (!is_array($inner)) return [202, ['status' => '無視しました']];
141 // 他人のアクティビティは取り消せない
142 if (Fedi::id($inner['actor'] ?? null) !== $actor) return [202, ['status' => '無視しました']];
143
144 switch ($inner['type'] ?? '') {
145 case 'Follow':
146 $target = Fedi::id($inner['object'] ?? null);
147 if ($target === Fedi::blogActorUrl()) return (new Activitypub())->handleInbox($a);
148 $username = $target ? Fedi::localUsername($target) : null;
149 if ($username !== null) {
150 Fedi::update(Fedi::userPath($username, 'followers.json'), function($l) use ($actor) { unset($l[$actor]); return $l; });
151 Fedi::update(Fedi::userPath($username, 'requests.json'), function($l) use ($actor) { unset($l[$actor]); return $l; });
152 }
153 break;
154 case 'Like':
155 self::modifyLocalNote(Fedi::id($inner['object'] ?? null), function($n) use ($actor) { unset($n['likes'][$actor]); return $n; });
156 break;
157 case 'Announce':
158 $obj = Fedi::id($inner['object'] ?? null);
159 self::modifyLocalNote($obj, function($n) use ($actor) { unset($n['boosts'][$actor]); return $n; });
160 if ($obj) Timeline::remove($obj, $actor);
161 break;
162 }
163 return [202, ['status' => 'OK']];
164 }
165
166 private static function create(array $a, string $actor, bool $local): array {
167 $obj = $a['object'] ?? null;
168 if (is_string($obj)) $obj = Remote::object($obj);
169 if (!is_array($obj) || !in_array($obj['type'] ?? '', ['Note', 'Article', 'Question', 'Page'], true)) return [202, ['status' => '無視しました']];
170 if (Fedi::id($obj['attributedTo'] ?? null) !== $actor) return [403, ['error' => '作者が違います']];
171 $id = Fedi::id($obj['id'] ?? null);
172 if ($id === null || Fedi::domainOf($id) !== Fedi::domainOf($actor)) return [403, ['error' => '不正なID']];
173
174 $addressed = self::addressedLocalUsers($obj);
175 $parent = Fedi::id($obj['inReplyTo'] ?? null);
176 $parentIds = $parent ? Fedi::localNoteId($parent) : null;
177
178 if (!$local) {
179 // 誰にも関係の無い投稿は保存しない(スパム対策)
180 $followers = self::localFollowersOf($actor);
181 if (empty($addressed) && empty($followers) && $parentIds === null) return [202, ['status' => '無視しました']];
182 $obj['_receivedAt'] = time();
183 Remote::store($obj);
184 Timeline::add($obj);
185 // 表示用にアクターをキャッシュする(1日1回まで取得)
186 Remote::actor($actor);
187 }
188
189 // 返信と通知
190 if ($parentIds !== null) {
191 Notes::modify($parentIds[1], function($n) use ($id) {
192 if (!in_array($id, $n['replies'] ?? [], true)) $n['replies'][] = $id;
193 return $n;
194 });
195 if ($parentIds[0] !== Fedi::localUsername($actor)) Actor::notify($parentIds[0], 'reply', $actor, $id);
196 }
197 foreach ($addressed as $u) {
198 if ($parentIds !== null && $u === $parentIds[0]) continue;
199 if (Fedi::localUsername($actor) === $u || Actor::isBlocked($u, $actor)) continue;
200 Actor::notify($u, 'mention', $actor, $id);
201 }
202 return [202, ['status' => 'OK']];
203 }
204
205 private static function update(array $a, string $actor): array {
206 $obj = $a['object'] ?? null;
207 if (!is_array($obj)) return [202, ['status' => '無視しました']];
208 if (Remote::isActor($obj)) {
209 if (($obj['id'] ?? null) === $actor) Remote::cacheActor($obj);
210 return [202, ['status' => 'OK']];
211 }
212 $id = Fedi::id($obj['id'] ?? null);
213 if ($id === null || Fedi::isLocal($id)) return [202, ['status' => 'OK']];
214 $old = Remote::stored($id);
215 if (!$old || Fedi::id($old['attributedTo'] ?? null) !== $actor || Fedi::id($obj['attributedTo'] ?? null) !== $actor) {
216 return [202, ['status' => '無視しました']];
217 }
218 $obj['_receivedAt'] = $old['_receivedAt'] ?? time();
219 Remote::store($obj);
220 Timeline::refresh($obj);
221 return [202, ['status' => 'OK']];
222 }
223
224 private static function delete(array $a, string $actor): array {
225 $id = Fedi::id($a['object'] ?? null);
226 if ($id === null) return [202, ['status' => '無視しました']];
227
228 if ($id === $actor) {
229 // アカウントの削除:全部から消す
230 $blog = (new Activitypub())->handleInbox($a);
231 foreach (Social::localUsernames() as $u) {
232 foreach (['followers.json', 'following.json', 'requests.json'] as $f) {
233 Fedi::update(Fedi::userPath($u, $f), function($l) use ($actor) { unset($l[$actor]); return $l; });
234 }
235 }
236 foreach (Timeline::entries() as $e) {
237 if ($e['author'] === $actor && !$e['local']) Remote::forget($e['object']);
238 }
239 Timeline::removeActor($actor);
240 Remote::forgetActor($actor);
241 return [202, ['status' => 'OK']];
242 }
243
244 $stored = Remote::stored($id);
245 if ($stored && Fedi::id($stored['attributedTo'] ?? null) === $actor) {
246 Remote::forget($id);
247 Timeline::remove($id);
248 $parent = Fedi::id($stored['inReplyTo'] ?? null);
249 self::modifyLocalNote($parent, function($n) use ($id) {
250 $n['replies'] = array_values(array_diff($n['replies'] ?? [], [$id]));
251 return $n;
252 });
253 }
254 return [202, ['status' => 'OK']];
255 }
256
257 private static function like(array $a, string $actor): array {
258 $obj = Fedi::id($a['object'] ?? null);
259 $ids = $obj ? Fedi::localNoteId($obj) : null;
260 if ($ids === null) return [202, ['status' => '無視しました']];
261 if (Actor::isBlocked($ids[0], $actor)) return [202, ['status' => '無視しました']];
262 $id = Fedi::id($a['id'] ?? null) ?? '';
263 self::modifyLocalNote($obj, function($n) use ($actor, $id) { $n['likes'][$actor] = $id; return $n; });
264 if (Fedi::localUsername($actor) !== $ids[0]) Actor::notify($ids[0], 'like', $actor, $obj);
265 return [202, ['status' => 'OK']];
266 }
267
268 private static function announce(array $a, string $actor, bool $local): array {
269 $objId = Fedi::id($a['object'] ?? null);
270 if ($objId === null) return [202, ['status' => '無視しました']];
271 $ids = Fedi::localNoteId($objId);
272 $id = Fedi::id($a['id'] ?? null) ?? '';
273
274 if ($ids !== null && !Actor::isBlocked($ids[0], $actor)) {
275 self::modifyLocalNote($objId, function($n) use ($actor, $id) { $n['boosts'][$actor] = $id; return $n; });
276 if (Fedi::localUsername($actor) !== $ids[0]) Actor::notify($ids[0], 'boost', $actor, $objId);
277 }
278 // フォローしている人のブーストはタイムラインに載せる
279 if (!$local && !empty(self::localFollowersOf($actor))) {
280 // 埋め込まれたオブジェクトは偽装出来るので、IDから取得する
281 $obj = Remote::object($objId);
282 if ($obj && in_array(Fedi::visibility(Fedi::ids($obj['to'] ?? []), Fedi::ids($obj['cc'] ?? [])), ['public', 'unlisted'], true)) {
283 if (!Fedi::isLocal($objId)) Remote::store($obj);
284 Timeline::add($obj, $actor, strtotime((string)($a['published'] ?? '')) ?: time());
285 }
286 }
287 return [202, ['status' => 'OK']];
288 }
289
290 private static function block(array $a, string $actor): array {
291 $target = Fedi::id($a['object'] ?? null);
292 $username = $target ? Fedi::localUsername($target) : null;
293 if ($username === null) return [202, ['status' => '無視しました']];
294 foreach (['followers.json', 'following.json', 'requests.json'] as $f) {
295 Fedi::update(Fedi::userPath($username, $f), function($l) use ($actor) { unset($l[$actor]); return $l; });
296 }
297 return [202, ['status' => 'OK']];
298 }
299
300 private static function flag(array $a, string $actor): array {
301 $objects = Fedi::ids($a['object'] ?? []);
302 if (empty($objects)) return [202, ['status' => '無視しました']];
303 Fedi::update(Fedi::path('reports.json'), function($l) use ($a, $actor, $objects) {
304 array_unshift($l, ['id' => Fedi::newId(), 'from' => $actor, 'actor' => $objects[0], 'objects' => array_slice($objects, 1),
305 'content' => mb_substr(Html::text((string)($a['content'] ?? '')), 0, 1000), 'at' => time(),
306 'remote' => true, 'resolved' => false]);
307 return array_slice($l, 0, 500);
308 });
309 return [202, ['status' => 'OK']];
310 }
311
312 //////
313
314 /**
315 * このアクターをフォローしているローカルのユーザー
316 */
317 public static function localFollowersOf(string $actor): array {
318 $out = [];
319 foreach (Social::localUsernames() as $u) {
320 if (Actor::isFollowing($u, $actor)) $out[] = $u;
321 }
322 return $out;
323 }
324
325 /**
326 * 投稿の宛先(to・cc・メンション)に含まれるローカルのユーザー
327 */
328 private static function addressedLocalUsers(array $obj): array {
329 $targets = array_merge(Fedi::ids($obj['to'] ?? []), Fedi::ids($obj['cc'] ?? []));
330 foreach ($obj['tag'] ?? [] as $t) {
331 if (is_array($t) && ($t['type'] ?? '') === 'Mention' && is_string($t['href'] ?? null)) $targets[] = $t['href'];
332 }
333 $out = [];
334 foreach (array_unique($targets) as $t) {
335 $u = Fedi::localUsername($t);
336 if ($u !== null && Fedi::localActor($u) !== null) $out[] = $u;
337 }
338 return array_values(array_unique($out));
339 }
340
341 private static function modifyLocalNote(?string $objectId, callable $fn): void {
342 $ids = $objectId ? Fedi::localNoteId($objectId) : null;
343 if ($ids) Notes::modify($ids[1], $fn);
344 }
345
346 /**
347 * UndoのobjectがIDだけの場合:このアクターの以前のアクティビティを探す(いいね・ブースト・フォロー)
348 */
349 private static function findOwnActivity(string $id, string $actor): ?array {
350 foreach (Timeline::entries() as $e) {
351 if (!$e['local'] || $e['type'] !== 'note') continue;
352 $ids = Fedi::localNoteId($e['object']);
353 $n = $ids ? Notes::get($ids[1]) : null;
354 if (!$n) continue;
355 if (($n['likes'][$actor] ?? null) === $id) return ['type' => 'Like', 'actor' => $actor, 'object' => $e['object']];
356 if (($n['boosts'][$actor] ?? null) === $id) return ['type' => 'Announce', 'actor' => $actor, 'object' => $e['object']];
357 }
358 return null;
359 }
360}