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