]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/actor.ts
More robust channel change federation
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / actor.ts
1 import * as Bluebird from 'bluebird'
2 import { Op, Transaction } from 'sequelize'
3 import { URL } from 'url'
4 import { v4 as uuidv4 } from 'uuid'
5 import { ActivityPubActor, ActivityPubActorType, ActivityPubOrderedCollection } from '../../../shared/models/activitypub'
6 import { ActivityPubAttributedTo } from '../../../shared/models/activitypub/objects'
7 import { checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
8 import { sanitizeAndCheckActorObject } from '../../helpers/custom-validators/activitypub/actor'
9 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
10 import { retryTransactionWrapper, updateInstanceWithAnother } from '../../helpers/database-utils'
11 import { logger } from '../../helpers/logger'
12 import { createPrivateAndPublicKeys } from '../../helpers/peertube-crypto'
13 import { doRequest } from '../../helpers/requests'
14 import { getUrlFromWebfinger } from '../../helpers/webfinger'
15 import { MIMETYPES, WEBSERVER } from '../../initializers/constants'
16 import { AccountModel } from '../../models/account/account'
17 import { ActorModel } from '../../models/activitypub/actor'
18 import { AvatarModel } from '../../models/avatar/avatar'
19 import { ServerModel } from '../../models/server/server'
20 import { VideoChannelModel } from '../../models/video/video-channel'
21 import { JobQueue } from '../job-queue'
22 import { ActorFetchByUrlType, fetchActorByUrl } from '../../helpers/actor'
23 import { sequelizeTypescript } from '../../initializers/database'
24 import {
25 MAccount,
26 MAccountDefault,
27 MActor,
28 MActorAccountChannelId,
29 MActorAccountChannelIdActor,
30 MActorAccountId,
31 MActorDefault,
32 MActorFull,
33 MActorFullActor,
34 MActorId,
35 MChannel
36 } from '../../types/models'
37 import { extname } from 'path'
38 import { getServerActor } from '@server/models/application/application'
39 import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
40
41 // Set account keys, this could be long so process after the account creation and do not block the client
42 function setAsyncActorKeys <T extends MActor> (actor: T) {
43 return createPrivateAndPublicKeys()
44 .then(({ publicKey, privateKey }) => {
45 actor.publicKey = publicKey
46 actor.privateKey = privateKey
47 return actor.save()
48 })
49 .catch(err => {
50 logger.error('Cannot set public/private keys of actor %d.', actor.url, { err })
51 return actor
52 })
53 }
54
55 function getOrCreateActorAndServerAndModel (
56 activityActor: string | ActivityPubActor,
57 fetchType: 'all',
58 recurseIfNeeded?: boolean,
59 updateCollections?: boolean
60 ): Promise<MActorFullActor>
61
62 function getOrCreateActorAndServerAndModel (
63 activityActor: string | ActivityPubActor,
64 fetchType?: 'association-ids',
65 recurseIfNeeded?: boolean,
66 updateCollections?: boolean
67 ): Promise<MActorAccountChannelId>
68
69 async function getOrCreateActorAndServerAndModel (
70 activityActor: string | ActivityPubActor,
71 fetchType: ActorFetchByUrlType = 'association-ids',
72 recurseIfNeeded = true,
73 updateCollections = false
74 ): Promise<MActorFullActor | MActorAccountChannelId> {
75 const actorUrl = getAPId(activityActor)
76 let created = false
77 let accountPlaylistsUrl: string
78
79 let actor = await fetchActorByUrl(actorUrl, fetchType)
80 // Orphan actor (not associated to an account of channel) so recreate it
81 if (actor && (!actor.Account && !actor.VideoChannel)) {
82 await actor.destroy()
83 actor = null
84 }
85
86 // We don't have this actor in our database, fetch it on remote
87 if (!actor) {
88 const { result } = await fetchRemoteActor(actorUrl)
89 if (result === undefined) throw new Error('Cannot fetch remote actor ' + actorUrl)
90
91 // Create the attributed to actor
92 // In PeerTube a video channel is owned by an account
93 let ownerActor: MActorFullActor
94 if (recurseIfNeeded === true && result.actor.type === 'Group') {
95 const accountAttributedTo = result.attributedTo.find(a => a.type === 'Person')
96 if (!accountAttributedTo) throw new Error('Cannot find account attributed to video channel ' + actor.url)
97
98 if (checkUrlsSameHost(accountAttributedTo.id, actorUrl) !== true) {
99 throw new Error(`Account attributed to ${accountAttributedTo.id} does not have the same host than actor url ${actorUrl}`)
100 }
101
102 try {
103 // Don't recurse another time
104 const recurseIfNeeded = false
105 ownerActor = await getOrCreateActorAndServerAndModel(accountAttributedTo.id, 'all', recurseIfNeeded)
106 } catch (err) {
107 logger.error('Cannot get or create account attributed to video channel ' + actorUrl)
108 throw new Error(err)
109 }
110 }
111
112 actor = await retryTransactionWrapper(saveActorAndServerAndModelIfNotExist, result, ownerActor)
113 created = true
114 accountPlaylistsUrl = result.playlists
115 }
116
117 if (actor.Account) (actor as MActorAccountChannelIdActor).Account.Actor = actor
118 if (actor.VideoChannel) (actor as MActorAccountChannelIdActor).VideoChannel.Actor = actor
119
120 const { actor: actorRefreshed, refreshed } = await retryTransactionWrapper(refreshActorIfNeeded, actor, fetchType)
121 if (!actorRefreshed) throw new Error('Actor ' + actor.url + ' does not exist anymore.')
122
123 if ((created === true || refreshed === true) && updateCollections === true) {
124 const payload = { uri: actor.outboxUrl, type: 'activity' as 'activity' }
125 await JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload })
126 }
127
128 // We created a new account: fetch the playlists
129 if (created === true && actor.Account && accountPlaylistsUrl) {
130 const payload = { uri: accountPlaylistsUrl, accountId: actor.Account.id, type: 'account-playlists' as 'account-playlists' }
131 await JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload })
132 }
133
134 return actorRefreshed
135 }
136
137 function buildActorInstance (type: ActivityPubActorType, url: string, preferredUsername: string, uuid?: string) {
138 return new ActorModel({
139 type,
140 url,
141 preferredUsername,
142 uuid,
143 publicKey: null,
144 privateKey: null,
145 followersCount: 0,
146 followingCount: 0,
147 inboxUrl: url + '/inbox',
148 outboxUrl: url + '/outbox',
149 sharedInboxUrl: WEBSERVER.URL + '/inbox',
150 followersUrl: url + '/followers',
151 followingUrl: url + '/following'
152 }) as MActor
153 }
154
155 async function updateActorInstance (actorInstance: ActorModel, attributes: ActivityPubActor) {
156 const followersCount = await fetchActorTotalItems(attributes.followers)
157 const followingCount = await fetchActorTotalItems(attributes.following)
158
159 actorInstance.type = attributes.type
160 actorInstance.preferredUsername = attributes.preferredUsername
161 actorInstance.url = attributes.id
162 actorInstance.publicKey = attributes.publicKey.publicKeyPem
163 actorInstance.followersCount = followersCount
164 actorInstance.followingCount = followingCount
165 actorInstance.inboxUrl = attributes.inbox
166 actorInstance.outboxUrl = attributes.outbox
167 actorInstance.followersUrl = attributes.followers
168 actorInstance.followingUrl = attributes.following
169
170 if (attributes.endpoints?.sharedInbox) {
171 actorInstance.sharedInboxUrl = attributes.endpoints.sharedInbox
172 }
173 }
174
175 type AvatarInfo = { name: string, onDisk: boolean, fileUrl: string }
176 async function updateActorAvatarInstance (actor: MActorDefault, info: AvatarInfo, t: Transaction) {
177 if (!info.name) return actor
178
179 if (actor.Avatar) {
180 // Don't update the avatar if the file URL did not change
181 if (info.fileUrl && actor.Avatar.fileUrl === info.fileUrl) return actor
182
183 try {
184 await actor.Avatar.destroy({ transaction: t })
185 } catch (err) {
186 logger.error('Cannot remove old avatar of actor %s.', actor.url, { err })
187 }
188 }
189
190 const avatar = await AvatarModel.create({
191 filename: info.name,
192 onDisk: info.onDisk,
193 fileUrl: info.fileUrl
194 }, { transaction: t })
195
196 actor.avatarId = avatar.id
197 actor.Avatar = avatar
198
199 return actor
200 }
201
202 async function deleteActorAvatarInstance (actor: MActorDefault, t: Transaction) {
203 try {
204 await actor.Avatar.destroy({ transaction: t })
205 } catch (err) {
206 logger.error('Cannot remove old avatar of actor %s.', actor.url, { err })
207 }
208
209 actor.avatarId = null
210 actor.Avatar = null
211
212 return actor
213 }
214
215 async function fetchActorTotalItems (url: string) {
216 const options = {
217 uri: url,
218 method: 'GET',
219 json: true,
220 activityPub: true
221 }
222
223 try {
224 const { body } = await doRequest<ActivityPubOrderedCollection<unknown>>(options)
225 return body.totalItems ? body.totalItems : 0
226 } catch (err) {
227 logger.warn('Cannot fetch remote actor count %s.', url, { err })
228 return 0
229 }
230 }
231
232 function getAvatarInfoIfExists (actorJSON: ActivityPubActor) {
233 const mimetypes = MIMETYPES.IMAGE
234 const icon = actorJSON.icon
235
236 if (!icon || icon.type !== 'Image' || !isActivityPubUrlValid(icon.url)) return undefined
237
238 let extension: string
239
240 if (icon.mediaType) {
241 extension = mimetypes.MIMETYPE_EXT[icon.mediaType]
242 } else {
243 const tmp = extname(icon.url)
244
245 if (mimetypes.EXT_MIMETYPE[tmp] !== undefined) extension = tmp
246 }
247
248 if (!extension) return undefined
249
250 return {
251 name: uuidv4() + extension,
252 fileUrl: icon.url
253 }
254 }
255
256 async function addFetchOutboxJob (actor: Pick<ActorModel, 'id' | 'outboxUrl'>) {
257 // Don't fetch ourselves
258 const serverActor = await getServerActor()
259 if (serverActor.id === actor.id) {
260 logger.error('Cannot fetch our own outbox!')
261 return undefined
262 }
263
264 const payload = {
265 uri: actor.outboxUrl,
266 type: 'activity' as 'activity'
267 }
268
269 return JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })
270 }
271
272 async function refreshActorIfNeeded <T extends MActorFull | MActorAccountChannelId> (
273 actorArg: T,
274 fetchedType: ActorFetchByUrlType
275 ): Promise<{ actor: T | MActorFull, refreshed: boolean }> {
276 if (!actorArg.isOutdated()) return { actor: actorArg, refreshed: false }
277
278 // We need more attributes
279 const actor = fetchedType === 'all'
280 ? actorArg as MActorFull
281 : await ActorModel.loadByUrlAndPopulateAccountAndChannel(actorArg.url)
282
283 try {
284 let actorUrl: string
285 try {
286 actorUrl = await getUrlFromWebfinger(actor.preferredUsername + '@' + actor.getHost())
287 } catch (err) {
288 logger.warn('Cannot get actor URL from webfinger, keeping the old one.', err)
289 actorUrl = actor.url
290 }
291
292 const { result, statusCode } = await fetchRemoteActor(actorUrl)
293
294 if (statusCode === HttpStatusCode.NOT_FOUND_404) {
295 logger.info('Deleting actor %s because there is a 404 in refresh actor.', actor.url)
296 actor.Account
297 ? await actor.Account.destroy()
298 : await actor.VideoChannel.destroy()
299
300 return { actor: undefined, refreshed: false }
301 }
302
303 if (result === undefined) {
304 logger.warn('Cannot fetch remote actor in refresh actor.')
305 return { actor, refreshed: false }
306 }
307
308 return sequelizeTypescript.transaction(async t => {
309 updateInstanceWithAnother(actor, result.actor)
310
311 if (result.avatar !== undefined) {
312 const avatarInfo = {
313 name: result.avatar.name,
314 fileUrl: result.avatar.fileUrl,
315 onDisk: false
316 }
317
318 await updateActorAvatarInstance(actor, avatarInfo, t)
319 }
320
321 // Force update
322 actor.setDataValue('updatedAt', new Date())
323 await actor.save({ transaction: t })
324
325 if (actor.Account) {
326 actor.Account.name = result.name
327 actor.Account.description = result.summary
328
329 await actor.Account.save({ transaction: t })
330 } else if (actor.VideoChannel) {
331 actor.VideoChannel.name = result.name
332 actor.VideoChannel.description = result.summary
333 actor.VideoChannel.support = result.support
334
335 await actor.VideoChannel.save({ transaction: t })
336 }
337
338 return { refreshed: true, actor }
339 })
340 } catch (err) {
341 logger.warn('Cannot refresh actor %s.', actor.url, { err })
342 return { actor, refreshed: false }
343 }
344 }
345
346 export {
347 getOrCreateActorAndServerAndModel,
348 buildActorInstance,
349 setAsyncActorKeys,
350 fetchActorTotalItems,
351 getAvatarInfoIfExists,
352 updateActorInstance,
353 deleteActorAvatarInstance,
354 refreshActorIfNeeded,
355 updateActorAvatarInstance,
356 addFetchOutboxJob
357 }
358
359 // ---------------------------------------------------------------------------
360
361 function saveActorAndServerAndModelIfNotExist (
362 result: FetchRemoteActorResult,
363 ownerActor?: MActorFullActor,
364 t?: Transaction
365 ): Bluebird<MActorFullActor> | Promise<MActorFullActor> {
366 const actor = result.actor
367
368 if (t !== undefined) return save(t)
369
370 return sequelizeTypescript.transaction(t => save(t))
371
372 async function save (t: Transaction) {
373 const actorHost = new URL(actor.url).host
374
375 const serverOptions = {
376 where: {
377 host: actorHost
378 },
379 defaults: {
380 host: actorHost
381 },
382 transaction: t
383 }
384 const [ server ] = await ServerModel.findOrCreate(serverOptions)
385
386 // Save our new account in database
387 actor.serverId = server.id
388
389 // Avatar?
390 if (result.avatar) {
391 const avatar = await AvatarModel.create({
392 filename: result.avatar.name,
393 fileUrl: result.avatar.fileUrl,
394 onDisk: false
395 }, { transaction: t })
396
397 actor.avatarId = avatar.id
398 }
399
400 // Force the actor creation, sometimes Sequelize skips the save() when it thinks the instance already exists
401 // (which could be false in a retried query)
402 const [ actorCreated, created ] = await ActorModel.findOrCreate<MActorFullActor>({
403 defaults: actor.toJSON(),
404 where: {
405 [Op.or]: [
406 {
407 url: actor.url
408 },
409 {
410 serverId: actor.serverId,
411 preferredUsername: actor.preferredUsername
412 }
413 ]
414 },
415 transaction: t
416 })
417
418 // Try to fix non HTTPS accounts of remote instances that fixed their URL afterwards
419 if (created !== true && actorCreated.url !== actor.url) {
420 // Only fix http://example.com/account/djidane to https://example.com/account/djidane
421 if (actorCreated.url.replace(/^http:\/\//, '') !== actor.url.replace(/^https:\/\//, '')) {
422 throw new Error(`Actor from DB with URL ${actorCreated.url} does not correspond to actor ${actor.url}`)
423 }
424
425 actorCreated.url = actor.url
426 await actorCreated.save({ transaction: t })
427 }
428
429 if (actorCreated.type === 'Person' || actorCreated.type === 'Application') {
430 actorCreated.Account = await saveAccount(actorCreated, result, t) as MAccountDefault
431 actorCreated.Account.Actor = actorCreated
432 } else if (actorCreated.type === 'Group') { // Video channel
433 const channel = await saveVideoChannel(actorCreated, result, ownerActor, t)
434 actorCreated.VideoChannel = Object.assign(channel, { Actor: actorCreated, Account: ownerActor.Account })
435 }
436
437 actorCreated.Server = server
438
439 return actorCreated
440 }
441 }
442
443 type FetchRemoteActorResult = {
444 actor: MActor
445 name: string
446 summary: string
447 support?: string
448 playlists?: string
449 avatar?: {
450 name: string
451 fileUrl: string
452 }
453 attributedTo: ActivityPubAttributedTo[]
454 }
455 async function fetchRemoteActor (actorUrl: string): Promise<{ statusCode?: number, result: FetchRemoteActorResult }> {
456 const options = {
457 uri: actorUrl,
458 method: 'GET',
459 json: true,
460 activityPub: true
461 }
462
463 logger.info('Fetching remote actor %s.', actorUrl)
464
465 const requestResult = await doRequest<ActivityPubActor>(options)
466 const actorJSON = requestResult.body
467
468 if (sanitizeAndCheckActorObject(actorJSON) === false) {
469 logger.debug('Remote actor JSON is not valid.', { actorJSON })
470 return { result: undefined, statusCode: requestResult.response.statusCode }
471 }
472
473 if (checkUrlsSameHost(actorJSON.id, actorUrl) !== true) {
474 logger.warn('Actor url %s has not the same host than its AP id %s', actorUrl, actorJSON.id)
475 return { result: undefined, statusCode: requestResult.response.statusCode }
476 }
477
478 const followersCount = await fetchActorTotalItems(actorJSON.followers)
479 const followingCount = await fetchActorTotalItems(actorJSON.following)
480
481 const actor = new ActorModel({
482 type: actorJSON.type,
483 preferredUsername: actorJSON.preferredUsername,
484 url: actorJSON.id,
485 publicKey: actorJSON.publicKey.publicKeyPem,
486 privateKey: null,
487 followersCount: followersCount,
488 followingCount: followingCount,
489 inboxUrl: actorJSON.inbox,
490 outboxUrl: actorJSON.outbox,
491 followersUrl: actorJSON.followers,
492 followingUrl: actorJSON.following,
493
494 sharedInboxUrl: actorJSON.endpoints?.sharedInbox
495 ? actorJSON.endpoints.sharedInbox
496 : null
497 })
498
499 const avatarInfo = await getAvatarInfoIfExists(actorJSON)
500
501 const name = actorJSON.name || actorJSON.preferredUsername
502 return {
503 statusCode: requestResult.response.statusCode,
504 result: {
505 actor,
506 name,
507 avatar: avatarInfo,
508 summary: actorJSON.summary,
509 support: actorJSON.support,
510 playlists: actorJSON.playlists,
511 attributedTo: actorJSON.attributedTo
512 }
513 }
514 }
515
516 async function saveAccount (actor: MActorId, result: FetchRemoteActorResult, t: Transaction) {
517 const [ accountCreated ] = await AccountModel.findOrCreate({
518 defaults: {
519 name: result.name,
520 description: result.summary,
521 actorId: actor.id
522 },
523 where: {
524 actorId: actor.id
525 },
526 transaction: t
527 })
528
529 return accountCreated as MAccount
530 }
531
532 async function saveVideoChannel (actor: MActorId, result: FetchRemoteActorResult, ownerActor: MActorAccountId, t: Transaction) {
533 const [ videoChannelCreated ] = await VideoChannelModel.findOrCreate({
534 defaults: {
535 name: result.name,
536 description: result.summary,
537 support: result.support,
538 actorId: actor.id,
539 accountId: ownerActor.Account.id
540 },
541 where: {
542 actorId: actor.id
543 },
544 transaction: t
545 })
546
547 return videoChannelCreated as MChannel
548 }