peertube-plugin-livechat/server/lib/configuration/channel/sanitize.ts

63 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-08-09 14:16:02 +00:00
import type { RegisterServerOptions } from '@peertube/peertube-types'
2023-09-18 10:23:35 +00:00
import type { ChannelConfigurationOptions } from '../../../../shared/lib/types'
2023-08-09 14:16:02 +00:00
/**
* Sanitize data so that they can safely be used/stored for channel configuration configuration.
2023-08-09 14:16:02 +00:00
* Throw an error if the format is obviously wrong.
* Cleans data (removing empty values, ...)
* @param options Peertube server options
* @param _channelInfos Channel infos
* @param data Input data
*/
async function sanitizeChannelConfigurationOptions (
2023-08-09 14:16:02 +00:00
_options: RegisterServerOptions,
2023-09-18 10:23:35 +00:00
_channelId: number | string,
2023-08-09 14:16:02 +00:00
data: any
): Promise<ChannelConfigurationOptions> {
2023-08-09 14:16:02 +00:00
const result = {
bot: false,
bannedJIDs: [],
forbiddenWords: []
}
if (typeof data !== 'object') {
throw new Error('Invalid data type')
}
// boolean fields
for (const f of ['bot']) {
if (!(f in data) || (typeof data[f] !== 'boolean')) {
throw new Error('Invalid data type for field ' + f)
}
result[f as keyof ChannelConfigurationOptions] = data[f]
2023-08-09 14:16:02 +00:00
}
// value/regexp array fields
for (const f of ['bannedJIDs', 'forbiddenWords']) {
if (!(f in data) || !Array.isArray(data[f])) {
throw new Error('Invalid data type for field ' + f)
}
for (const v of data[f]) {
if (typeof v !== 'string') {
throw new Error('Invalid data type in a value of field ' + f)
}
if (v === '' || /^\s+$/.test(v)) {
// ignore empty values
continue
}
// value must be a valid regexp
try {
// eslint-disable-next-line no-new
new RegExp(v)
} catch (_err) {
throw new Error('Invalid value in field ' + f)
}
(result[f as keyof ChannelConfigurationOptions] as string[]).push(v)
2023-08-09 14:16:02 +00:00
}
}
return result
}
export {
sanitizeChannelConfigurationOptions
2023-08-09 14:16:02 +00:00
}