audiobookshelf/server/utils/htmlSanitizer.js

40 lines
1.0 KiB
JavaScript
Raw Normal View History

const sanitizeHtml = require('../libs/sanitizeHtml')
2023-02-25 22:05:44 +01:00
const { entities } = require("./htmlEntities");
function sanitize(html) {
const sanitizerOptions = {
allowedTags: [
2023-02-25 22:05:44 +01:00
'p', 'ol', 'ul', 'li', 'a', 'strong', 'em', 'del', 'br'
],
disallowedTagsMode: 'discard',
allowedAttributes: {
a: ['href', 'name', 'target']
},
allowedSchemes: ['http', 'https', 'mailto'],
allowProtocolRelative: false
}
return sanitizeHtml(html, sanitizerOptions)
}
module.exports.sanitize = sanitize
function stripAllTags(html, shouldDecodeEntities = true) {
const sanitizerOptions = {
allowedTags: [],
disallowedTagsMode: 'discard'
}
let sanitized = sanitizeHtml(html, sanitizerOptions)
return shouldDecodeEntities ? decodeHTMLEntities(sanitized) : sanitized
}
module.exports.stripAllTags = stripAllTags
function decodeHTMLEntities(strToDecode) {
2022-08-31 03:15:18 +02:00
return strToDecode.replace(/\&([^;]+);?/g, function (entity) {
if (entity in entities) {
return entities[entity]
}
return entity;
})
}