]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/activitypub/actor.ts
More robust channel change federation
[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
1ca9f7c3 42function setAsyncActorKeys <T extends MActor> (actor: T) {
50d6de9c
C
43 return createPrivateAndPublicKeys()
44 .then(({ publicKey, privateKey }) => {
453e83ea
C
45 actor.publicKey = publicKey
46 actor.privateKey = privateKey
50d6de9c
C
47 return actor.save()
48 })
49 .catch(err => {
57cfff78 50 logger.error('Cannot set public/private keys of actor %d.', actor.url, { err })
50d6de9c
C
51 return actor
52 })
53}
54
453e83ea
C
55function getOrCreateActorAndServerAndModel (
56 activityActor: string | ActivityPubActor,
57 fetchType: 'all',
58 recurseIfNeeded?: boolean,
59 updateCollections?: boolean
60): Promise<MActorFullActor>
61
62function getOrCreateActorAndServerAndModel (
63 activityActor: string | ActivityPubActor,
64 fetchType?: 'association-ids',
65 recurseIfNeeded?: boolean,
66 updateCollections?: boolean
67): Promise<MActorAccountChannelId>
68
687d638c
C
69async function getOrCreateActorAndServerAndModel (
70 activityActor: string | ActivityPubActor,
453e83ea 71 fetchType: ActorFetchByUrlType = 'association-ids',
687d638c
C
72 recurseIfNeeded = true,
73 updateCollections = false
453e83ea 74): Promise<MActorFullActor | MActorAccountChannelId> {
848f499d 75 const actorUrl = getAPId(activityActor)
687d638c 76 let created = false
418d092a 77 let accountPlaylistsUrl: string
6be84cbc 78
e587e0ec 79 let actor = await fetchActorByUrl(actorUrl, fetchType)
25e4d6ee 80 // Orphan actor (not associated to an account of channel) so recreate it
6104adc3 81 if (actor && (!actor.Account && !actor.VideoChannel)) {
25e4d6ee
C
82 await actor.destroy()
83 actor = null
84 }
50d6de9c
C
85
86 // We don't have this actor in our database, fetch it on remote
87 if (!actor) {
f5b0af50 88 const { result } = await fetchRemoteActor(actorUrl)
601527d7 89 if (result === undefined) throw new Error('Cannot fetch remote actor ' + actorUrl)
50d6de9c
C
90
91 // Create the attributed to actor
92 // In PeerTube a video channel is owned by an account
453e83ea 93 let ownerActor: MActorFullActor
50d6de9c
C
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
5c6d985f
C
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
50d6de9c 102 try {
5c6d985f 103 // Don't recurse another time
418d092a
C
104 const recurseIfNeeded = false
105 ownerActor = await getOrCreateActorAndServerAndModel(accountAttributedTo.id, 'all', recurseIfNeeded)
50d6de9c 106 } catch (err) {
471251fa 107 logger.error('Cannot get or create account attributed to video channel ' + actorUrl)
50d6de9c
C
108 throw new Error(err)
109 }
110 }
111
90d4bb81 112 actor = await retryTransactionWrapper(saveActorAndServerAndModelIfNotExist, result, ownerActor)
687d638c 113 created = true
418d092a 114 accountPlaylistsUrl = result.playlists
50d6de9c
C
115 }
116
453e83ea
C
117 if (actor.Account) (actor as MActorAccountChannelIdActor).Account.Actor = actor
118 if (actor.VideoChannel) (actor as MActorAccountChannelIdActor).VideoChannel.Actor = actor
d9bdd007 119
e587e0ec 120 const { actor: actorRefreshed, refreshed } = await retryTransactionWrapper(refreshActorIfNeeded, actor, fetchType)
652c6416 121 if (!actorRefreshed) throw new Error('Actor ' + actor.url + ' does not exist anymore.')
f5b0af50 122
687d638c
C
123 if ((created === true || refreshed === true) && updateCollections === true) {
124 const payload = { uri: actor.outboxUrl, type: 'activity' as 'activity' }
a1587156 125 await JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload })
687d638c
C
126 }
127
418d092a
C
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' }
a1587156 131 await JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload })
418d092a
C
132 }
133
687d638c 134 return actorRefreshed
50d6de9c
C
135}
136
c5911fd3
C
137function 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',
6dd9de95 149 sharedInboxUrl: WEBSERVER.URL + '/inbox',
c5911fd3
C
150 followersUrl: url + '/followers',
151 followingUrl: url + '/following'
1ca9f7c3 152 }) as MActor
c5911fd3
C
153}
154
a5625b41
C
155async function updateActorInstance (actorInstance: ActorModel, attributes: ActivityPubActor) {
156 const followersCount = await fetchActorTotalItems(attributes.followers)
157 const followingCount = await fetchActorTotalItems(attributes.following)
158
57cfff78
C
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
57cfff78
C
167 actorInstance.followersUrl = attributes.followers
168 actorInstance.followingUrl = attributes.following
47581df0 169
faa9d434 170 if (attributes.endpoints?.sharedInbox) {
47581df0
C
171 actorInstance.sharedInboxUrl = attributes.endpoints.sharedInbox
172 }
a5625b41
C
173}
174
453e83ea
C
175type AvatarInfo = { name: string, onDisk: boolean, fileUrl: string }
176async function updateActorAvatarInstance (actor: MActorDefault, info: AvatarInfo, t: Transaction) {
66fb2aa3 177 if (!info.name) return actor
a5625b41 178
66fb2aa3 179 if (actor.Avatar) {
1c5fbed2
C
180 // Don't update the avatar if the file URL did not change
181 if (info.fileUrl && actor.Avatar.fileUrl === info.fileUrl) return actor
a5625b41 182
66fb2aa3
C
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 }
a5625b41
C
188 }
189
66fb2aa3
C
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
557b13ae 199 return actor
a5625b41
C
200}
201
1ea7da81
RK
202async 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
265ba139
C
215async function fetchActorTotalItems (url: string) {
216 const options = {
217 uri: url,
218 method: 'GET',
219 json: true,
220 activityPub: true
221 }
222
265ba139 223 try {
bdd428a6 224 const { body } = await doRequest<ActivityPubOrderedCollection<unknown>>(options)
7006bc63 225 return body.totalItems ? body.totalItems : 0
265ba139 226 } catch (err) {
d5b7d911 227 logger.warn('Cannot fetch remote actor count %s.', url, { err })
7006bc63 228 return 0
265ba139 229 }
265ba139
C
230}
231
a1587156 232function getAvatarInfoIfExists (actorJSON: ActivityPubActor) {
c6de3a85
C
233 const mimetypes = MIMETYPES.IMAGE
234 const icon = actorJSON.icon
235
236 if (!icon || icon.type !== 'Image' || !isActivityPubUrlValid(icon.url)) return undefined
265ba139 237
5224f713
C
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 }
c6de3a85
C
247
248 if (!extension) return undefined
249
250 return {
251 name: uuidv4() + extension,
252 fileUrl: icon.url
253 }
265ba139
C
254}
255
5224c394 256async function addFetchOutboxJob (actor: Pick<ActorModel, 'id' | 'outboxUrl'>) {
16f29007
C
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 = {
f6eebcb3
C
265 uri: actor.outboxUrl,
266 type: 'activity' as 'activity'
16f29007
C
267 }
268
269 return JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })
270}
271
453e83ea
C
272async function refreshActorIfNeeded <T extends MActorFull | MActorAccountChannelId> (
273 actorArg: T,
744d0eca 274 fetchedType: ActorFetchByUrlType
453e83ea 275): Promise<{ actor: T | MActorFull, refreshed: boolean }> {
744d0eca
C
276 if (!actorArg.isOutdated()) return { actor: actorArg, refreshed: false }
277
278 // We need more attributes
453e83ea
C
279 const actor = fetchedType === 'all'
280 ? actorArg as MActorFull
281 : await ActorModel.loadByUrlAndPopulateAccountAndChannel(actorArg.url)
744d0eca
C
282
283 try {
699b059e
C
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
744d0eca
C
292 const { result, statusCode } = await fetchRemoteActor(actorUrl)
293
f2eb23cd 294 if (statusCode === HttpStatusCode.NOT_FOUND_404) {
744d0eca 295 logger.info('Deleting actor %s because there is a 404 in refresh actor.', actor.url)
a1587156
C
296 actor.Account
297 ? await actor.Account.destroy()
298 : await actor.VideoChannel.destroy()
299
744d0eca
C
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
557b13ae
C
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)
744d0eca
C
319 }
320
321 // Force update
322 actor.setDataValue('updatedAt', new Date())
323 await actor.save({ transaction: t })
324
325 if (actor.Account) {
6b9c966f
C
326 actor.Account.name = result.name
327 actor.Account.description = result.summary
744d0eca
C
328
329 await actor.Account.save({ transaction: t })
330 } else if (actor.VideoChannel) {
6b9c966f
C
331 actor.VideoChannel.name = result.name
332 actor.VideoChannel.description = result.summary
333 actor.VideoChannel.support = result.support
744d0eca
C
334
335 await actor.VideoChannel.save({ transaction: t })
336 }
337
338 return { refreshed: true, actor }
339 })
340 } catch (err) {
4ee7a4c9 341 logger.warn('Cannot refresh actor %s.', actor.url, { err })
744d0eca
C
342 return { actor, refreshed: false }
343 }
344}
345
c5911fd3
C
346export {
347 getOrCreateActorAndServerAndModel,
348 buildActorInstance,
265ba139
C
349 setAsyncActorKeys,
350 fetchActorTotalItems,
557b13ae 351 getAvatarInfoIfExists,
a5625b41 352 updateActorInstance,
1ea7da81 353 deleteActorAvatarInstance,
744d0eca 354 refreshActorIfNeeded,
16f29007
C
355 updateActorAvatarInstance,
356 addFetchOutboxJob
c5911fd3
C
357}
358
359// ---------------------------------------------------------------------------
360
50d6de9c
C
361function saveActorAndServerAndModelIfNotExist (
362 result: FetchRemoteActorResult,
453e83ea 363 ownerActor?: MActorFullActor,
50d6de9c 364 t?: Transaction
453e83ea 365): Bluebird<MActorFullActor> | Promise<MActorFullActor> {
a1587156 366 const actor = result.actor
50d6de9c
C
367
368 if (t !== undefined) return save(t)
369
370 return sequelizeTypescript.transaction(t => save(t))
371
372 async function save (t: Transaction) {
a1587156 373 const actorHost = new URL(actor.url).host
50d6de9c
C
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
557b13ae 387 actor.serverId = server.id
50d6de9c 388
c5911fd3 389 // Avatar?
557b13ae 390 if (result.avatar) {
c5911fd3 391 const avatar = await AvatarModel.create({
557b13ae
C
392 filename: result.avatar.name,
393 fileUrl: result.avatar.fileUrl,
394 onDisk: false
c5911fd3 395 }, { transaction: t })
557b13ae
C
396
397 actor.avatarId = avatar.id
c5911fd3
C
398 }
399
50d6de9c
C
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)
5147a6d9 402 const [ actorCreated, created ] = await ActorModel.findOrCreate<MActorFullActor>({
2c897999
C
403 defaults: actor.toJSON(),
404 where: {
5147a6d9
C
405 [Op.or]: [
406 {
407 url: actor.url
408 },
409 {
410 serverId: actor.serverId,
411 preferredUsername: actor.preferredUsername
412 }
413 ]
2c897999
C
414 },
415 transaction: t
416 })
50d6de9c 417
5147a6d9
C
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
e26dc0cd 421 if (actorCreated.url.replace(/^http:\/\//, '') !== actor.url.replace(/^https:\/\//, '')) {
5147a6d9
C
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
50d6de9c 429 if (actorCreated.type === 'Person' || actorCreated.type === 'Application') {
0283eaac 430 actorCreated.Account = await saveAccount(actorCreated, result, t) as MAccountDefault
50d6de9c
C
431 actorCreated.Account.Actor = actorCreated
432 } else if (actorCreated.type === 'Group') { // Video channel
0283eaac
C
433 const channel = await saveVideoChannel(actorCreated, result, ownerActor, t)
434 actorCreated.VideoChannel = Object.assign(channel, { Actor: actorCreated, Account: ownerActor.Account })
50d6de9c
C
435 }
436
883993c8
C
437 actorCreated.Server = server
438
50d6de9c
C
439 return actorCreated
440 }
441}
442
443type FetchRemoteActorResult = {
453e83ea 444 actor: MActor
e12a0092 445 name: string
50d6de9c 446 summary: string
2422c46b 447 support?: string
418d092a 448 playlists?: string
557b13ae 449 avatar?: {
a1587156 450 name: string
557b13ae
C
451 fileUrl: string
452 }
50d6de9c
C
453 attributedTo: ActivityPubAttributedTo[]
454}
f5b0af50 455async function fetchRemoteActor (actorUrl: string): Promise<{ statusCode?: number, result: FetchRemoteActorResult }> {
50d6de9c
C
456 const options = {
457 uri: actorUrl,
458 method: 'GET',
da854ddd
C
459 json: true,
460 activityPub: true
50d6de9c
C
461 }
462
463 logger.info('Fetching remote actor %s.', actorUrl)
464
4c280004 465 const requestResult = await doRequest<ActivityPubActor>(options)
4c280004 466 const actorJSON = requestResult.body
9977c128
C
467
468 if (sanitizeAndCheckActorObject(actorJSON) === false) {
b4593cd7 469 logger.debug('Remote actor JSON is not valid.', { actorJSON })
f5b0af50 470 return { result: undefined, statusCode: requestResult.response.statusCode }
50d6de9c
C
471 }
472
5c6d985f 473 if (checkUrlsSameHost(actorJSON.id, actorUrl) !== true) {
9f79ade6
C
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 }
5c6d985f
C
476 }
477
50d6de9c
C
478 const followersCount = await fetchActorTotalItems(actorJSON.followers)
479 const followingCount = await fetchActorTotalItems(actorJSON.following)
480
481 const actor = new ActorModel({
482 type: actorJSON.type,
e12a0092
C
483 preferredUsername: actorJSON.preferredUsername,
484 url: actorJSON.id,
50d6de9c
C
485 publicKey: actorJSON.publicKey.publicKeyPem,
486 privateKey: null,
487 followersCount: followersCount,
488 followingCount: followingCount,
489 inboxUrl: actorJSON.inbox,
490 outboxUrl: actorJSON.outbox,
50d6de9c 491 followersUrl: actorJSON.followers,
47581df0
C
492 followingUrl: actorJSON.following,
493
faa9d434 494 sharedInboxUrl: actorJSON.endpoints?.sharedInbox
47581df0 495 ? actorJSON.endpoints.sharedInbox
a82ddfad 496 : null
50d6de9c
C
497 })
498
557b13ae 499 const avatarInfo = await getAvatarInfoIfExists(actorJSON)
c5911fd3 500
e12a0092 501 const name = actorJSON.name || actorJSON.preferredUsername
50d6de9c 502 return {
f5b0af50
C
503 statusCode: requestResult.response.statusCode,
504 result: {
505 actor,
506 name,
557b13ae 507 avatar: avatarInfo,
f5b0af50
C
508 summary: actorJSON.summary,
509 support: actorJSON.support,
418d092a 510 playlists: actorJSON.playlists,
f5b0af50
C
511 attributedTo: actorJSON.attributedTo
512 }
50d6de9c
C
513 }
514}
515
453e83ea 516async function saveAccount (actor: MActorId, result: FetchRemoteActorResult, t: Transaction) {
2c897999
C
517 const [ accountCreated ] = await AccountModel.findOrCreate({
518 defaults: {
519 name: result.name,
2422c46b 520 description: result.summary,
2c897999
C
521 actorId: actor.id
522 },
523 where: {
524 actorId: actor.id
525 },
526 transaction: t
50d6de9c
C
527 })
528
453e83ea 529 return accountCreated as MAccount
50d6de9c
C
530}
531
453e83ea 532async function saveVideoChannel (actor: MActorId, result: FetchRemoteActorResult, ownerActor: MActorAccountId, t: Transaction) {
2c897999
C
533 const [ videoChannelCreated ] = await VideoChannelModel.findOrCreate({
534 defaults: {
535 name: result.name,
536 description: result.summary,
2422c46b 537 support: result.support,
2c897999
C
538 actorId: actor.id,
539 accountId: ownerActor.Account.id
540 },
541 where: {
542 actorId: actor.id
543 },
544 transaction: t
50d6de9c
C
545 })
546
453e83ea 547 return videoChannelCreated as MChannel
50d6de9c 548}