]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/custom-validators/activitypub/misc.ts
Merge branch 'master' into develop
[github/Chocobozzz/PeerTube.git] / server / helpers / custom-validators / activitypub / misc.ts
1 import * as validator from 'validator'
2 import { CONSTRAINTS_FIELDS } from '../../../initializers/constants'
3 import { isTestInstance } from '../../core-utils'
4 import { exists } from '../misc'
5
6 function isUrlValid (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)
21 }
22
23 function isActivityPubUrlValid (url: string) {
24 return isUrlValid(url) && validator.isLength('' + url, CONSTRAINTS_FIELDS.ACTORS.URL)
25 }
26
27 function isBaseActivityValid (activity: any, type: string) {
28 return activity.type === type &&
29 isActivityPubUrlValid(activity.id) &&
30 isObjectValid(activity.actor) &&
31 isUrlCollectionValid(activity.to) &&
32 isUrlCollectionValid(activity.cc)
33 }
34
35 function isUrlCollectionValid (collection: any) {
36 return collection === undefined ||
37 (Array.isArray(collection) && collection.every(t => isActivityPubUrlValid(t)))
38 }
39
40 function isObjectValid (object: any) {
41 return exists(object) &&
42 (
43 isActivityPubUrlValid(object) || isActivityPubUrlValid(object.id)
44 )
45 }
46
47 function setValidAttributedTo (obj: any) {
48 if (Array.isArray(obj.attributedTo) === false) {
49 obj.attributedTo = []
50 return true
51 }
52
53 obj.attributedTo = obj.attributedTo.filter(a => {
54 return (a.type === 'Group' || a.type === 'Person') && isActivityPubUrlValid(a.id)
55 })
56
57 return true
58 }
59
60 export {
61 isUrlValid,
62 isActivityPubUrlValid,
63 isBaseActivityValid,
64 setValidAttributedTo,
65 isObjectValid
66 }