PeerTube/server/helpers/custom-validators/activitypub/misc.ts

77 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-01-07 07:56:07 -06:00
import validator from 'validator'
2022-08-11 03:43:31 -05:00
import { CONFIG } from '@server/initializers/config'
import { CONSTRAINTS_FIELDS } from '../../../initializers/constants'
2017-12-12 10:53:50 -06:00
import { exists } from '../misc'
2017-11-09 10:51:58 -06:00
2018-09-11 09:27:07 -05:00
function isUrlValid (url: string) {
2017-11-09 10:51:58 -06:00
const isURLOptions = {
require_host: true,
require_tld: true,
require_protocol: true,
require_valid_protocol: true,
protocols: [ 'http', 'https' ]
}
2017-11-14 03:57:56 -06:00
// We validate 'localhost', so we don't have the top level domain
if (CONFIG.WEBSERVER.HOSTNAME === 'localhost' || CONFIG.WEBSERVER.HOSTNAME === '127.0.0.1') {
2017-11-14 03:57:56 -06:00
isURLOptions.require_tld = false
}
2018-09-11 09:27:07 -05:00
return exists(url) && validator.isURL('' + url, isURLOptions)
}
function isActivityPubUrlValid (url: string) {
return isUrlValid(url) && validator.isLength('' + url, CONSTRAINTS_FIELDS.ACTORS.URL)
2017-11-09 10:51:58 -06:00
}
2017-11-10 07:34:45 -06:00
function isBaseActivityValid (activity: any, type: string) {
2019-05-13 07:51:43 -05:00
return activity.type === type &&
2017-11-14 10:31:26 -06:00
isActivityPubUrlValid(activity.id) &&
isObjectValid(activity.actor) &&
isUrlCollectionValid(activity.to) &&
isUrlCollectionValid(activity.cc)
}
function isUrlCollectionValid (collection: any) {
return collection === undefined ||
(Array.isArray(collection) && collection.every(t => isActivityPubUrlValid(t)))
}
function isObjectValid (object: any) {
return exists(object) &&
2017-11-17 08:20:42 -06:00
(
isActivityPubUrlValid(object) || isActivityPubUrlValid(object.id)
2017-11-14 10:31:26 -06:00
)
2017-11-10 07:34:45 -06:00
}
2017-12-14 10:38:41 -06:00
function setValidAttributedTo (obj: any) {
if (Array.isArray(obj.attributedTo) === false) {
obj.attributedTo = []
return true
}
2018-08-28 11:29:29 -05:00
obj.attributedTo = obj.attributedTo.filter(a => {
return isActivityPubUrlValid(a) ||
((a.type === 'Group' || a.type === 'Person') && isActivityPubUrlValid(a.id))
2017-12-14 10:38:41 -06:00
})
return true
}
function isActivityPubVideoDurationValid (value: string) {
// https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
return exists(value) &&
typeof value === 'string' &&
value.startsWith('PT') &&
value.endsWith('S')
}
2017-11-09 10:51:58 -06:00
export {
2018-09-11 09:27:07 -05:00
isUrlValid,
2017-11-10 07:34:45 -06:00
isActivityPubUrlValid,
2017-12-14 10:38:41 -06:00
isBaseActivityValid,
setValidAttributedTo,
isObjectValid,
isActivityPubVideoDurationValid
2017-11-09 10:51:58 -06:00
}