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