65f5ca80924ca9b106fafe9b223b035ab1434fed
[oweals/peertube.git] / server / helpers / custom-validators / activitypub / misc.ts
1 import * as validator from 'validator'
2 import { CONSTRAINTS_FIELDS } from '../../../initializers'
3 import { isTestInstance } from '../../core-utils'
4 import { exists } from '../misc'
5
6 function isActivityPubUrlValid (url: string) {
7   const isURLOptions = {
8     require_host: true,
9     require_tld: true,
10     require_protocol: true,
11     require_valid_protocol: true,
12     protocols: [ 'http', 'https' ]
13   }
14
15   // We validate 'localhost', so we don't have the top level domain
16   if (isTestInstance()) {
17     isURLOptions.require_tld = false
18   }
19
20   return exists(url) && validator.isURL(url, isURLOptions) && validator.isLength(url, CONSTRAINTS_FIELDS.ACCOUNTS.URL)
21 }
22
23 function isBaseActivityValid (activity: any, type: string) {
24   return (activity['@context'] === undefined || Array.isArray(activity['@context'])) &&
25     activity.type === type &&
26     isActivityPubUrlValid(activity.id) &&
27     isActivityPubUrlValid(activity.actor) &&
28     (
29       activity.to === undefined ||
30       (Array.isArray(activity.to) && activity.to.every(t => isActivityPubUrlValid(t)))
31     ) &&
32     (
33       activity.cc === undefined ||
34       (Array.isArray(activity.cc) && activity.cc.every(t => isActivityPubUrlValid(t)))
35     )
36 }
37
38 export {
39   isActivityPubUrlValid,
40   isBaseActivityValid
41 }