-
-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathdispatchers.ts
More file actions
1386 lines (1216 loc) · 44.9 KB
/
dispatchers.ts
File metadata and controls
1386 lines (1216 loc) · 44.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* TODO: Break this file into separate class-based handlers/dispatchers
* @see ADR-0005: Class-based architecture
*
* This file violates our architectural patterns and should be refactored.
*/
import {
Accept,
Announce,
Article,
Create,
Follow,
Group,
Image,
importJwk,
Like,
Note,
Person,
type Protocol,
Undo,
Update,
verifyObject,
} from '@fedify/fedify';
import * as Sentry from '@sentry/node';
import type { AccountService } from '@/account/account.service';
import type { FollowersService } from '@/activitypub/followers.service';
import type { FedifyContext, FedifyRequestContext } from '@/app';
import { ACTIVITYPUB_COLLECTION_PAGE_SIZE } from '@/constants';
import { exhaustiveCheck, getError, getValue, isError } from '@/core/result';
import {
buildAnnounceActivityForPost,
buildCreateActivityAndObjectFromPost,
} from '@/helpers/activitypub/activity';
import { isFollowedByDefaultSiteAccount } from '@/helpers/activitypub/actor';
import type { HostDataContextLoader } from '@/http/host-data-context-loader';
import { lookupActor, lookupObject } from '@/lookup-helpers';
import { OutboxType, type Post } from '@/post/post.entity';
import type { KnexPostRepository } from '@/post/post.repository.knex';
import type { PostService } from '@/post/post.service';
export const actorDispatcher = (hostDataContextLoader: HostDataContextLoader) =>
async function actorDispatcher(
ctx: FedifyRequestContext,
identifier: string,
) {
const hostData = await hostDataContextLoader.loadDataForHost(ctx.host);
if (isError(hostData)) {
const error = getError(hostData);
switch (error) {
case 'site-not-found':
ctx.data.logger.error('Site not found for {host}', {
host: ctx.host,
});
return null;
case 'account-not-found':
ctx.data.logger.error('Account not found for {host}', {
host: ctx.host,
});
return null;
case 'multiple-users-for-site':
ctx.data.logger.error('Multiple users found for {host}', {
host: ctx.host,
});
return null;
default:
exhaustiveCheck(error);
}
}
const { account } = getValue(hostData);
const person = new Person({
id: new URL(account.apId),
name: account.name,
summary: account.bio,
preferredUsername: account.username,
icon: account.avatarUrl
? new Image({
url: new URL(account.avatarUrl),
})
: null,
image: account.bannerImageUrl
? new Image({
url: new URL(account.bannerImageUrl),
})
: null,
inbox: account.apInbox,
outbox: account.apOutbox,
following: account.apFollowing,
followers: account.apFollowers,
liked: account.apLiked,
url: account.url || account.apId,
publicKeys: (await ctx.getActorKeyPairs(identifier)).map(
(key) => key.cryptographicKey,
),
});
return person;
};
export const keypairDispatcher = (
accountService: AccountService,
hostDataContextLoader: HostDataContextLoader,
) => {
const MAX_CACHE_SIZE = 1000;
const KEY_TTL_MS = 30 * 60 * 1000; // 30 minutes
const cryptoKeyCache = new Map<
number,
{
publicKey: CryptoKey;
privateKey: CryptoKey;
createdAt: number;
}
>();
return async function keypairDispatcher(
ctx: FedifyContext,
identifier: string,
) {
const hostData = await hostDataContextLoader.loadDataForHost(ctx.host);
if (isError(hostData)) {
const error = getError(hostData);
switch (error) {
case 'site-not-found':
ctx.data.logger.error(
'Site not found for {host} (identifier: {identifier})',
{
host: ctx.host,
identifier,
},
);
return [];
case 'account-not-found':
ctx.data.logger.error(
'Account not found for {host} (identifier: {identifier})',
{
host: ctx.host,
identifier,
},
);
return [];
case 'multiple-users-for-site':
ctx.data.logger.error(
'Multiple users found for {host} (identifier: {identifier})',
{
host: ctx.host,
identifier,
},
);
return [];
default:
exhaustiveCheck(error);
}
}
const { account } = getValue(hostData);
const cached = cryptoKeyCache.get(account.id);
if (cached) {
if (Date.now() - cached.createdAt < KEY_TTL_MS) {
return [cached];
}
cryptoKeyCache.delete(account.id);
}
const keyPair = await accountService.getKeyPair(account.id);
if (isError(keyPair)) {
const error = getError(keyPair);
switch (error) {
case 'account-not-found':
ctx.data.logger.error(
'Account not found for {host} (identifier: {identifier})',
{
host: ctx.host,
identifier,
},
);
return [];
case 'key-pair-not-found':
ctx.data.logger.error(
'Key pair not found for {host} (identifier: {identifier})',
{
host: ctx.host,
identifier,
},
);
return [];
default:
exhaustiveCheck(error);
}
}
const { publicKey, privateKey } = getValue(keyPair);
try {
const imported = {
publicKey: await importJwk(
JSON.parse(publicKey) as JsonWebKey,
'public',
),
privateKey: await importJwk(
JSON.parse(privateKey) as JsonWebKey,
'private',
),
};
const now = Date.now();
// Evict expired entries
for (const [key, entry] of cryptoKeyCache) {
if (now - entry.createdAt >= KEY_TTL_MS) {
cryptoKeyCache.delete(key);
}
}
// If still full, evict the oldest entry
if (cryptoKeyCache.size >= MAX_CACHE_SIZE) {
let oldestKey: number | undefined;
let oldestTime = Infinity;
for (const [key, entry] of cryptoKeyCache) {
if (entry.createdAt < oldestTime) {
oldestTime = entry.createdAt;
oldestKey = key;
}
}
if (oldestKey !== undefined) {
cryptoKeyCache.delete(oldestKey);
}
}
cryptoKeyCache.set(account.id, {
...imported,
createdAt: now,
});
return [imported];
} catch (error) {
ctx.data.logger.error(
'Could not parse keypair for {host} (identifier: {identifier}): {error}',
{
host: ctx.host,
identifier,
error,
},
);
return [];
}
};
};
export function createAcceptHandler(accountService: AccountService) {
return async function handleAccept(ctx: FedifyContext, accept: Accept) {
ctx.data.logger.debug('Handling Accept');
const parsed = ctx.parseUri(accept.objectId);
ctx.data.logger.debug('Parsed accept object', { parsed });
if (!accept.id) {
ctx.data.logger.debug('Accept missing id - exit');
return;
}
const sender = await accept.getActor(ctx);
ctx.data.logger.debug('Accept sender retrieved');
if (sender === null || sender.id === null) {
ctx.data.logger.debug('Sender missing, exit early');
return;
}
const object = await accept.getObject();
if (object instanceof Follow === false) {
ctx.data.logger.debug('Accept object is not a Follow, exit early');
return;
}
const recipient = await object.getActor();
if (recipient === null || recipient.id === null) {
ctx.data.logger.debug('Recipient missing, exit early');
return;
}
// Parallelize JSON-LD serialization to reduce latency
const [senderJson, acceptJson] = await Promise.all([
sender.toJsonLd(),
accept.toJsonLd(),
]);
await Promise.all([
ctx.data.globaldb.set([accept.id.href], acceptJson),
ctx.data.globaldb.set([sender.id.href], senderJson),
]);
// Record the account of the sender as well as the follow
const followerAccountResult = await accountService.ensureByApId(
recipient.id,
);
if (isError(followerAccountResult)) {
ctx.data.logger.debug('Follower account not found, exit early');
return;
}
const followerAccount = getValue(followerAccountResult);
const ensureAccountToFollowResult = await accountService.ensureByApId(
sender.id,
);
if (isError(ensureAccountToFollowResult)) {
ctx.data.logger.debug('Account to follow not found, exit early');
return;
}
const accountToFollow = getValue(ensureAccountToFollowResult);
await accountService.followAccount(followerAccount, accountToFollow);
};
}
export async function handleAnnouncedCreate(
ctx: FedifyContext,
announce: Announce,
accountService: AccountService,
postService: PostService,
hostDataContextLoader: HostDataContextLoader,
) {
ctx.data.logger.debug('Handling Announced Create');
// Validate announced create activity is from a Group as we only support
// announcements from Groups - See https://codeberg.org/fediverse/fep/src/branch/main/fep/1b12/fep-1b12.md
const announcer = await announce.getActor(ctx);
if (!(announcer instanceof Group)) {
ctx.data.logger.debug('Create is not from a Group, exit early');
return;
}
const hostData = await hostDataContextLoader.loadDataForHost(ctx.host);
if (isError(hostData)) {
const error = getError(hostData);
switch (error) {
case 'site-not-found':
ctx.data.logger.error('Site not found for {host}', {
host: ctx.host,
});
throw new Error(`Site not found for host: ${ctx.host}`);
case 'account-not-found':
ctx.data.logger.error('Account not found for {host}', {
host: ctx.host,
});
throw new Error(`Account not found for host: ${ctx.host}`);
case 'multiple-users-for-site':
ctx.data.logger.error('Multiple users found for {host}', {
host: ctx.host,
});
throw new Error(`Multiple users found for host: ${ctx.host}`);
default:
exhaustiveCheck(error);
}
}
const { site } = getValue(hostData);
// Validate that the group is followed
if (
!(await isFollowedByDefaultSiteAccount(announcer, site, accountService))
) {
ctx.data.logger.debug('Group is not followed, exit early');
return;
}
let create: Create | null = null;
let createJson: Awaited<ReturnType<Create['toJsonLd']>> | undefined;
// Verify create activity
create = (await announce.getObject()) as Create;
if (!create.id) {
ctx.data.logger.debug('Create missing id, exit early');
return;
}
if (create.proofId || create.proofIds.length > 0) {
ctx.data.logger.debug('Verifying create with proof(s)');
// Cache the JSON-LD result to avoid redundant serialization later
createJson = await create.toJsonLd();
if ((await verifyObject(Create, createJson)) === null) {
ctx.data.logger.info(
'Create cannot be verified with provided proof(s), exit early',
);
return;
}
} else {
ctx.data.logger.debug('Verifying create with network lookup');
const lookupResult = await lookupObject(ctx, create.id);
if (lookupResult === null) {
ctx.data.logger.debug(
'Create cannot be verified with network lookup due to inability to lookup object, exit early',
);
return;
}
if (
lookupResult instanceof Create &&
String(create.id) !== String(lookupResult.id)
) {
ctx.data.logger.debug(
'Create cannot be verified with network lookup due to local activity + remote activity ID mismatch, exit early',
);
return;
}
if (
lookupResult instanceof Create &&
lookupResult.id?.origin !== lookupResult.actorId?.origin
) {
ctx.data.logger.debug(
'Create cannot be verified with network lookup due to remote activity + actor origin mismatch, exit early',
);
return;
}
if (
(lookupResult instanceof Note || lookupResult instanceof Article) &&
create.objectId?.href !== lookupResult.id?.href
) {
ctx.data.logger.debug(
'Create cannot be verified with network lookup due to lookup returning Object and ID mismatch, exit early',
);
return;
}
// If everything checks out, use the remote create activity where we can
// so that we can guarantee the integrity of the associated object (i.e
// the object of the annouced activity has not been tampered with). We can
// only do this if the lookupResult is a Create (which is not always the
// case depending on the remote server's implementation - i.e WordPress is
// returning the Note/Article object instead of a Create object).
if (lookupResult instanceof Create) {
create = lookupResult;
}
if (!create.id) {
ctx.data.logger.debug('Remote create missing id, exit early');
return;
}
}
// Persist create activity - use cached JSON-LD if available (from proof verification)
// Otherwise serialize now (happens when create was replaced via network lookup)
if (!createJson) {
createJson = await create.toJsonLd();
}
ctx.data.globaldb.set([create.id.href], createJson);
if (!create.objectId) {
ctx.data.logger.debug('Create object id missing, exit early');
return;
}
// This handles storing the posts in the posts table
const postResult = await postService.getByApId(create.objectId);
if (isError(postResult)) {
const error = getError(postResult);
switch (error) {
case 'upstream-error':
ctx.data.logger.debug(
'Upstream error fetching post for create handling',
{
postId: create.objectId.href,
},
);
break;
case 'not-a-post':
ctx.data.logger.debug(
'Resource is not a post in create handling',
{
postId: create.objectId.href,
},
);
break;
case 'missing-author':
ctx.data.logger.debug(
'Post has missing author in create handling',
{
postId: create.objectId.href,
},
);
break;
default:
exhaustiveCheck(error);
}
} else {
// Add a repost of the post from the announcer so that followers of the
// announcer can see the post in their feed
const post = getValue(postResult);
if (announcer.id === null) {
ctx.data.logger.debug('Announcer id missing, exit early');
return;
}
const accountResult = await accountService.ensureByApId(announcer.id);
if (isError(accountResult)) {
ctx.data.logger.debug('Announcer account not found, exit early');
return;
}
const account = getValue(accountResult);
post.addRepost(account);
await postService.repostByApId(account, post.apId);
}
}
export const createUndoHandler = (
accountService: AccountService,
postRepository: KnexPostRepository,
postService: PostService,
) =>
async function handleUndo(ctx: FedifyContext, undo: Undo) {
ctx.data.logger.debug('Handling Undo');
if (!undo.id) {
ctx.data.logger.debug('Undo missing an id - exiting');
return;
}
const object = await undo.getObject();
if (object instanceof Follow) {
const follow = object as Follow;
if (!follow.actorId || !follow.objectId) {
ctx.data.logger.debug('Undo contains invalid Follow - exiting');
return;
}
const [unfollower, unfollowing] = await Promise.all([
accountService.getAccountByApId(follow.actorId.href),
accountService.getAccountByApId(follow.objectId.href),
]);
if (!unfollower) {
ctx.data.logger.debug('Could not find unfollower');
return;
}
if (!unfollowing) {
ctx.data.logger.debug('Could not find unfollowing');
return;
}
await ctx.data.globaldb.set([undo.id.href], await undo.toJsonLd());
await accountService.recordAccountUnfollow(unfollowing, unfollower);
} else if (object instanceof Announce) {
const sender = await object.getActor(ctx);
if (sender === null || sender.id === null) {
ctx.data.logger.debug(
'Undo announce activity sender missing, exit early',
);
return;
}
const senderAccount = await accountService.getByApId(sender.id);
if (object.objectId === null) {
ctx.data.logger.debug(
'Undo announce activity object id missing, exit early',
);
return;
}
if (senderAccount !== null) {
const originalPostResult = await postService.getByApId(
object.objectId,
);
if (isError(originalPostResult)) {
const error = getError(originalPostResult);
switch (error) {
case 'upstream-error':
ctx.data.logger.debug(
'Upstream error fetching post for undoing announce',
{
postId: object.objectId.href,
},
);
break;
case 'not-a-post':
ctx.data.logger.debug(
'Resource is not a post in undoing announce',
{
postId: object.objectId.href,
},
);
break;
case 'missing-author':
ctx.data.logger.debug(
'Post has missing author in undoing announce',
{
postId: object.objectId.href,
},
);
break;
default:
return exhaustiveCheck(error);
}
return;
}
const originalPost = getValue(originalPostResult);
originalPost.removeRepost(senderAccount);
await postRepository.save(originalPost);
}
}
return;
};
export function createAnnounceHandler(
accountService: AccountService,
postService: PostService,
postRepository: KnexPostRepository,
hostDataContextLoader: HostDataContextLoader,
) {
return async function handleAnnounce(
ctx: FedifyContext,
announce: Announce,
) {
ctx.data.logger.debug('Handling Announce');
if (!announce.id) {
// Validate announce
ctx.data.logger.debug('Invalid Announce - no id');
return;
}
if (!announce.objectId) {
ctx.data.logger.debug('Invalid Announce - no object id');
return;
}
// Check what was announced - If it's an Activity rather than an Object
// (which can occur if the announcer is a Group - See
// https://codeberg.org/fediverse/fep/src/branch/main/fep/1b12/fep-1b12.md),
// we need to forward the announce on to an appropriate handler
// This routing is something that should be handled by Fedify, but has
// not yet been implemented - Tracked here: https://github.com/dahlia/fedify/issues/193
const announced = await lookupObject(ctx, announce.objectId);
if (announced instanceof Create) {
return handleAnnouncedCreate(
ctx,
announce,
accountService,
postService,
hostDataContextLoader,
);
}
// Validate sender
const sender = await announce.getActor(ctx);
if (sender === null || sender.id === null) {
ctx.data.logger.debug('Announce sender missing, exit early');
return;
}
// Lookup announced object - If not found in globalDb
let object = null;
const existing =
(await ctx.data.globaldb.get([announce.objectId.href])) ?? null;
if (!existing) {
ctx.data.logger.debug(
'Announce object not found in globalDb, performing network lookup',
);
// Reuse the already-fetched object from the Create check above
// instead of calling lookupObject again
object = announced;
}
if (!existing && !object) {
// Validate object
ctx.data.logger.debug('Invalid Announce - could not find object');
return;
}
if (object && !object.id) {
ctx.data.logger.debug(
'Invalid Announce - could not find object id',
);
return;
}
// Persist announce
const announceJson = (await announce.toJsonLd()) as {
object: object | string;
[key: string]: unknown;
};
if (existing) {
// If the announced object already exists in globalDb, set it on
// the activity
announceJson.object = existing;
}
if (!existing && object && object.id) {
// Persist object if not already persisted
ctx.data.logger.debug('Storing object in globalDb');
const objectJson = await object.toJsonLd();
if (typeof objectJson === 'object' && objectJson !== null) {
if (
'attributedTo' in objectJson &&
typeof objectJson.attributedTo === 'string'
) {
const actor = await lookupActor(
ctx,
objectJson.attributedTo,
);
objectJson.attributedTo = await actor?.toJsonLd();
}
}
ctx.data.globaldb.set([object.id.href], objectJson);
// Set the full object on the activity
announceJson.object = objectJson as object;
}
ctx.data.globaldb.set([announce.id.href], announceJson);
// This will save the account if it doesn't already exist
const senderAccount = await accountService.getByApId(sender.id);
if (senderAccount !== null) {
// This will save the post if it doesn't already exist
const postResult = await postService.getByApId(announce.objectId);
if (isError(postResult)) {
const error = getError(postResult);
switch (error) {
case 'upstream-error':
ctx.data.logger.debug(
'Upstream error fetching post for reposting',
{
postId: announce.objectId.href,
},
);
break;
case 'not-a-post':
ctx.data.logger.debug(
'Resource for reposting is not a post',
{
postId: announce.objectId.href,
},
);
break;
case 'missing-author':
ctx.data.logger.debug(
'Post for reposting has missing author',
{
postId: announce.objectId.href,
},
);
break;
default:
return exhaustiveCheck(error);
}
} else {
const post = getValue(postResult);
post.addRepost(senderAccount);
await postRepository.save(post);
}
}
};
}
export function createLikeHandler(
accountService: AccountService,
postRepository: KnexPostRepository,
postService: PostService,
) {
return async function handleLike(ctx: FedifyContext, like: Like) {
ctx.data.logger.debug('Handling Like');
// Validate like
if (!like.id) {
ctx.data.logger.debug('Invalid Like - no id');
return;
}
if (!like.objectId) {
ctx.data.logger.debug('Invalid Like - no object id');
return;
}
if (!like.actorId) {
ctx.data.logger.debug('Invalid Like - no actor id');
return;
}
const account = await accountService.getByApId(like.actorId);
if (account !== null) {
const postResult = await postService.getByApId(like.objectId);
if (isError(postResult)) {
const error = getError(postResult);
switch (error) {
case 'upstream-error':
ctx.data.logger.debug(
'Upstream error fetching post for liking',
{
postId: like.objectId.href,
},
);
break;
case 'not-a-post':
ctx.data.logger.debug(
'Resource for liking is not a post',
{
postId: like.objectId.href,
},
);
break;
case 'missing-author':
ctx.data.logger.debug(
'Post for liking has missing author',
{
postId: like.objectId.href,
},
);
break;
default: {
return exhaustiveCheck(error);
}
}
} else {
const post = getValue(postResult);
post.addLike(account);
await postRepository.save(post);
}
}
// Validate sender
const sender = await like.getActor(ctx);
if (sender === null || sender.id === null) {
ctx.data.logger.debug('Like sender missing, exit early');
return;
}
// Lookup liked object - If not found in globalDb, perform network lookup
let object = null;
const existing =
(await ctx.data.globaldb.get([like.objectId.href])) ?? null;
if (!existing) {
ctx.data.logger.debug(
'Like object not found in globalDb, performing network lookup',
);
try {
object = await like.getObject();
} catch (err) {
ctx.data.logger.debug(
'Error performing like object network lookup',
{
error: err,
},
);
}
}
// Validate object
if (!existing && !object) {
ctx.data.logger.debug('Invalid Like - could not find object');
return;
}
if (object && !object.id) {
ctx.data.logger.debug('Invalid Like - could not find object id');
return;
}
// Persist like
const likeJson = await like.toJsonLd();
ctx.data.globaldb.set([like.id.href], likeJson);
// Persist object if not already persisted
if (!existing && object && object.id) {
ctx.data.logger.debug('Storing object in globalDb');
const objectJson = await object.toJsonLd();
ctx.data.globaldb.set([object.id.href], objectJson);
}
};
}
export async function inboxErrorHandler(ctx: FedifyContext, error: unknown) {
if (process.env.USE_MQ !== 'true') {
Sentry.captureException(error);
}
ctx.data.logger.error('Error handling incoming activity: {error}', {
error,
});
}
export function createFollowersDispatcher(
followersService: FollowersService,
hostDataContextLoader: HostDataContextLoader,
) {
return async function dispatchFollowers(
ctx: FedifyContext,
_handle: string,
) {
const hostData = await hostDataContextLoader.loadDataForHost(ctx.host);
if (isError(hostData)) {
const error = getError(hostData);
switch (error) {
case 'site-not-found':
ctx.data.logger.error('Site not found for {host}', {
host: ctx.host,
});
throw new Error(`Site not found for host: ${ctx.host}`);
case 'account-not-found':
ctx.data.logger.error('Account not found for {host}', {
host: ctx.host,
});
throw new Error(`Account not found for host: ${ctx.host}`);
case 'multiple-users-for-site':
ctx.data.logger.error('Multiple users found for {host}', {
host: ctx.host,
});
throw new Error(
`Multiple users found for host: ${ctx.host}`,
);
default:
exhaustiveCheck(error);
}
}
const { account } = getValue(hostData);
const followers = await followersService.getFollowers(account.id);
return {
items: followers,
};
};
}
export function createFollowingDispatcher(
accountService: AccountService,
hostDataContextLoader: HostDataContextLoader,
) {
return async function dispatchFollowing(
ctx: FedifyRequestContext,
_handle: string,
cursor: string | null,
) {
ctx.data.logger.debug('Following Dispatcher');
const offset = Number.parseInt(cursor ?? '0', 10);
let nextCursor: string | null = null;
const host = ctx.request.headers.get('host')!;
const hostData = await hostDataContextLoader.loadDataForHost(host);
if (isError(hostData)) {
const error = getError(hostData);
switch (error) {
case 'site-not-found':
ctx.data.logger.error('Site not found for {host}', {
host,
});
throw new Error(`Site not found for host: ${host}`);
case 'account-not-found':
ctx.data.logger.error('Account not found for {host}', {
host,