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