misc.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. function isUrlValid (url: string) {
  6. const isURLOptions = {
  7. require_host: true,
  8. require_tld: true,
  9. require_protocol: true,
  10. require_valid_protocol: true,
  11. protocols: [ 'http', 'https' ]
  12. }
  13. // We validate 'localhost', so we don't have the top level domain
  14. if (isTestInstance()) {
  15. isURLOptions.require_tld = false
  16. }
  17. return exists(url) && validator.isURL('' + url, isURLOptions)
  18. }
  19. function isActivityPubUrlValid (url: string) {
  20. return isUrlValid(url) && validator.isLength('' + url, CONSTRAINTS_FIELDS.ACTORS.URL)
  21. }
  22. function isBaseActivityValid (activity: any, type: string) {
  23. return activity.type === type &&
  24. isActivityPubUrlValid(activity.id) &&
  25. isObjectValid(activity.actor) &&
  26. isUrlCollectionValid(activity.to) &&
  27. isUrlCollectionValid(activity.cc)
  28. }
  29. function isUrlCollectionValid (collection: any) {
  30. return collection === undefined ||
  31. (Array.isArray(collection) && collection.every(t => isActivityPubUrlValid(t)))
  32. }
  33. function isObjectValid (object: any) {
  34. return exists(object) &&
  35. (
  36. isActivityPubUrlValid(object) || isActivityPubUrlValid(object.id)
  37. )
  38. }
  39. function setValidAttributedTo (obj: any) {
  40. if (Array.isArray(obj.attributedTo) === false) {
  41. obj.attributedTo = []
  42. return true
  43. }
  44. obj.attributedTo = obj.attributedTo.filter(a => {
  45. return (a.type === 'Group' || a.type === 'Person') && isActivityPubUrlValid(a.id)
  46. })
  47. return true
  48. }
  49. export {
  50. isUrlValid,
  51. isActivityPubUrlValid,
  52. isBaseActivityValid,
  53. setValidAttributedTo,
  54. isObjectValid
  55. }