]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/actor.ts
emails: remove hardcoded PeerTube names
[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 ' + actor.url)
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 fetchActorTotalItems (url: string) {
203 const options = {
204 uri: url,
205 method: 'GET',
206 json: true,
207 activityPub: true
208 }
209
210 try {
211 const { body } = await doRequest<ActivityPubOrderedCollection<unknown>>(options)
212 return body.totalItems ? body.totalItems : 0
213 } catch (err) {
214 logger.warn('Cannot fetch remote actor count %s.', url, { err })
215 return 0
216 }
217 }
218
219 function getAvatarInfoIfExists (actorJSON: ActivityPubActor) {
220 const mimetypes = MIMETYPES.IMAGE
221 const icon = actorJSON.icon
222
223 if (!icon || icon.type !== 'Image' || !isActivityPubUrlValid(icon.url)) return undefined
224
225 let extension: string
226
227 if (icon.mediaType) {
228 extension = mimetypes.MIMETYPE_EXT[icon.mediaType]
229 } else {
230 const tmp = extname(icon.url)
231
232 if (mimetypes.EXT_MIMETYPE[tmp] !== undefined) extension = tmp
233 }
234
235 if (!extension) return undefined
236
237 return {
238 name: uuidv4() + extension,
239 fileUrl: icon.url
240 }
241 }
242
243 async function addFetchOutboxJob (actor: Pick<ActorModel, 'id' | 'outboxUrl'>) {
244 // Don't fetch ourselves
245 const serverActor = await getServerActor()
246 if (serverActor.id === actor.id) {
247 logger.error('Cannot fetch our own outbox!')
248 return undefined
249 }
250
251 const payload = {
252 uri: actor.outboxUrl,
253 type: 'activity' as 'activity'
254 }
255
256 return JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })
257 }
258
259 async function refreshActorIfNeeded <T extends MActorFull | MActorAccountChannelId> (
260 actorArg: T,
261 fetchedType: ActorFetchByUrlType
262 ): Promise<{ actor: T | MActorFull, refreshed: boolean }> {
263 if (!actorArg.isOutdated()) return { actor: actorArg, refreshed: false }
264
265 // We need more attributes
266 const actor = fetchedType === 'all'
267 ? actorArg as MActorFull
268 : await ActorModel.loadByUrlAndPopulateAccountAndChannel(actorArg.url)
269
270 try {
271 let actorUrl: string
272 try {
273 actorUrl = await getUrlFromWebfinger(actor.preferredUsername + '@' + actor.getHost())
274 } catch (err) {
275 logger.warn('Cannot get actor URL from webfinger, keeping the old one.', err)
276 actorUrl = actor.url
277 }
278
279 const { result, statusCode } = await fetchRemoteActor(actorUrl)
280
281 if (statusCode === HttpStatusCode.NOT_FOUND_404) {
282 logger.info('Deleting actor %s because there is a 404 in refresh actor.', actor.url)
283 actor.Account
284 ? await actor.Account.destroy()
285 : await actor.VideoChannel.destroy()
286
287 return { actor: undefined, refreshed: false }
288 }
289
290 if (result === undefined) {
291 logger.warn('Cannot fetch remote actor in refresh actor.')
292 return { actor, refreshed: false }
293 }
294
295 return sequelizeTypescript.transaction(async t => {
296 updateInstanceWithAnother(actor, result.actor)
297
298 if (result.avatar !== undefined) {
299 const avatarInfo = {
300 name: result.avatar.name,
301 fileUrl: result.avatar.fileUrl,
302 onDisk: false
303 }
304
305 await updateActorAvatarInstance(actor, avatarInfo, t)
306 }
307
308 // Force update
309 actor.setDataValue('updatedAt', new Date())
310 await actor.save({ transaction: t })
311
312 if (actor.Account) {
313 actor.Account.name = result.name
314 actor.Account.description = result.summary
315
316 await actor.Account.save({ transaction: t })
317 } else if (actor.VideoChannel) {
318 actor.VideoChannel.name = result.name
319 actor.VideoChannel.description = result.summary
320 actor.VideoChannel.support = result.support
321
322 await actor.VideoChannel.save({ transaction: t })
323 }
324
325 return { refreshed: true, actor }
326 })
327 } catch (err) {
328 logger.warn('Cannot refresh actor %s.', actor.url, { err })
329 return { actor, refreshed: false }
330 }
331 }
332
333 export {
334 getOrCreateActorAndServerAndModel,
335 buildActorInstance,
336 setAsyncActorKeys,
337 fetchActorTotalItems,
338 getAvatarInfoIfExists,
339 updateActorInstance,
340 refreshActorIfNeeded,
341 updateActorAvatarInstance,
342 addFetchOutboxJob
343 }
344
345 // ---------------------------------------------------------------------------
346
347 function saveActorAndServerAndModelIfNotExist (
348 result: FetchRemoteActorResult,
349 ownerActor?: MActorFullActor,
350 t?: Transaction
351 ): Bluebird<MActorFullActor> | Promise<MActorFullActor> {
352 const actor = result.actor
353
354 if (t !== undefined) return save(t)
355
356 return sequelizeTypescript.transaction(t => save(t))
357
358 async function save (t: Transaction) {
359 const actorHost = new URL(actor.url).host
360
361 const serverOptions = {
362 where: {
363 host: actorHost
364 },
365 defaults: {
366 host: actorHost
367 },
368 transaction: t
369 }
370 const [ server ] = await ServerModel.findOrCreate(serverOptions)
371
372 // Save our new account in database
373 actor.serverId = server.id
374
375 // Avatar?
376 if (result.avatar) {
377 const avatar = await AvatarModel.create({
378 filename: result.avatar.name,
379 fileUrl: result.avatar.fileUrl,
380 onDisk: false
381 }, { transaction: t })
382
383 actor.avatarId = avatar.id
384 }
385
386 // Force the actor creation, sometimes Sequelize skips the save() when it thinks the instance already exists
387 // (which could be false in a retried query)
388 const [ actorCreated, created ] = await ActorModel.findOrCreate<MActorFullActor>({
389 defaults: actor.toJSON(),
390 where: {
391 [Op.or]: [
392 {
393 url: actor.url
394 },
395 {
396 serverId: actor.serverId,
397 preferredUsername: actor.preferredUsername
398 }
399 ]
400 },
401 transaction: t
402 })
403
404 // Try to fix non HTTPS accounts of remote instances that fixed their URL afterwards
405 if (created !== true && actorCreated.url !== actor.url) {
406 // Only fix http://example.com/account/djidane to https://example.com/account/djidane
407 if (actorCreated.url.replace(/^http:\/\//, '') !== actor.url.replace(/^https:\/\//, '')) {
408 throw new Error(`Actor from DB with URL ${actorCreated.url} does not correspond to actor ${actor.url}`)
409 }
410
411 actorCreated.url = actor.url
412 await actorCreated.save({ transaction: t })
413 }
414
415 if (actorCreated.type === 'Person' || actorCreated.type === 'Application') {
416 actorCreated.Account = await saveAccount(actorCreated, result, t) as MAccountDefault
417 actorCreated.Account.Actor = actorCreated
418 } else if (actorCreated.type === 'Group') { // Video channel
419 const channel = await saveVideoChannel(actorCreated, result, ownerActor, t)
420 actorCreated.VideoChannel = Object.assign(channel, { Actor: actorCreated, Account: ownerActor.Account })
421 }
422
423 actorCreated.Server = server
424
425 return actorCreated
426 }
427 }
428
429 type FetchRemoteActorResult = {
430 actor: MActor
431 name: string
432 summary: string
433 support?: string
434 playlists?: string
435 avatar?: {
436 name: string
437 fileUrl: string
438 }
439 attributedTo: ActivityPubAttributedTo[]
440 }
441 async function fetchRemoteActor (actorUrl: string): Promise<{ statusCode?: number, result: FetchRemoteActorResult }> {
442 const options = {
443 uri: actorUrl,
444 method: 'GET',
445 json: true,
446 activityPub: true
447 }
448
449 logger.info('Fetching remote actor %s.', actorUrl)
450
451 const requestResult = await doRequest<ActivityPubActor>(options)
452 const actorJSON = requestResult.body
453
454 if (sanitizeAndCheckActorObject(actorJSON) === false) {
455 logger.debug('Remote actor JSON is not valid.', { actorJSON })
456 return { result: undefined, statusCode: requestResult.response.statusCode }
457 }
458
459 if (checkUrlsSameHost(actorJSON.id, actorUrl) !== true) {
460 logger.warn('Actor url %s has not the same host than its AP id %s', actorUrl, actorJSON.id)
461 return { result: undefined, statusCode: requestResult.response.statusCode }
462 }
463
464 const followersCount = await fetchActorTotalItems(actorJSON.followers)
465 const followingCount = await fetchActorTotalItems(actorJSON.following)
466
467 const actor = new ActorModel({
468 type: actorJSON.type,
469 preferredUsername: actorJSON.preferredUsername,
470 url: actorJSON.id,
471 publicKey: actorJSON.publicKey.publicKeyPem,
472 privateKey: null,
473 followersCount: followersCount,
474 followingCount: followingCount,
475 inboxUrl: actorJSON.inbox,
476 outboxUrl: actorJSON.outbox,
477 followersUrl: actorJSON.followers,
478 followingUrl: actorJSON.following,
479
480 sharedInboxUrl: actorJSON.endpoints?.sharedInbox
481 ? actorJSON.endpoints.sharedInbox
482 : null
483 })
484
485 const avatarInfo = await getAvatarInfoIfExists(actorJSON)
486
487 const name = actorJSON.name || actorJSON.preferredUsername
488 return {
489 statusCode: requestResult.response.statusCode,
490 result: {
491 actor,
492 name,
493 avatar: avatarInfo,
494 summary: actorJSON.summary,
495 support: actorJSON.support,
496 playlists: actorJSON.playlists,
497 attributedTo: actorJSON.attributedTo
498 }
499 }
500 }
501
502 async function saveAccount (actor: MActorId, result: FetchRemoteActorResult, t: Transaction) {
503 const [ accountCreated ] = await AccountModel.findOrCreate({
504 defaults: {
505 name: result.name,
506 description: result.summary,
507 actorId: actor.id
508 },
509 where: {
510 actorId: actor.id
511 },
512 transaction: t
513 })
514
515 return accountCreated as MAccount
516 }
517
518 async function saveVideoChannel (actor: MActorId, result: FetchRemoteActorResult, ownerActor: MActorAccountId, t: Transaction) {
519 const [ videoChannelCreated ] = await VideoChannelModel.findOrCreate({
520 defaults: {
521 name: result.name,
522 description: result.summary,
523 support: result.support,
524 actorId: actor.id,
525 accountId: ownerActor.Account.id
526 },
527 where: {
528 actorId: actor.id
529 },
530 transaction: t
531 })
532
533 return videoChannelCreated as MChannel
534 }