New option to use and configure Prosody mod_firewall WIP (#97):
* new setting * new configuration screen for Peertube admins * include the mod_firewall module * load mod_firewall if enabled * sys admin can disable the firewall config editing by creating a special file on the disk * user documentation
This commit is contained in:
131
client/common/admin/firewall/elements/admin-firewall.ts
Normal file
131
client/common/admin/firewall/elements/admin-firewall.ts
Normal file
@ -0,0 +1,131 @@
|
||||
// SPDX-FileCopyrightText: 2024 John Livingston <https://www.john-livingston.fr/>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
import type { AdminFirewallConfiguration } from 'shared/lib/types'
|
||||
import { AdminFirewallService } from '../services/admin-firewall'
|
||||
import { LivechatElement } from '../../../lib/elements/livechat'
|
||||
import { ValidationError, ValidationErrorType } from '../../../lib/models/validation'
|
||||
import { tplAdminFirewall } from '../templates/admin-firewall'
|
||||
import { TemplateResult, html, nothing } from 'lit'
|
||||
import { customElement, state } from 'lit/decorators.js'
|
||||
import { Task } from '@lit/task'
|
||||
|
||||
@customElement('livechat-admin-firewall')
|
||||
export class AdminFirewallElement extends LivechatElement {
|
||||
private _adminFirewallService?: AdminFirewallService
|
||||
|
||||
@state()
|
||||
public firewallConfiguration?: AdminFirewallConfiguration
|
||||
|
||||
@state()
|
||||
public validationError?: ValidationError
|
||||
|
||||
@state()
|
||||
public actionDisabled: boolean = false
|
||||
|
||||
private _asyncTaskRender: Task
|
||||
|
||||
constructor () {
|
||||
super()
|
||||
this._asyncTaskRender = this._initTask()
|
||||
}
|
||||
|
||||
protected _initTask (): Task {
|
||||
return new Task(this, {
|
||||
task: async () => {
|
||||
this._adminFirewallService = new AdminFirewallService(this.ptOptions)
|
||||
this.firewallConfiguration = await this._adminFirewallService.fetchConfiguration()
|
||||
this.actionDisabled = false // in case of reset
|
||||
},
|
||||
args: () => []
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the form by reloading data from backend.
|
||||
*/
|
||||
public async reset (event?: Event): Promise<void> {
|
||||
event?.preventDefault()
|
||||
this.actionDisabled = true
|
||||
this._asyncTaskRender = this._initTask()
|
||||
this.requestUpdate()
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the validation errors.
|
||||
* @param ev the vent
|
||||
*/
|
||||
public resetValidation (_ev?: Event): void {
|
||||
if (this.validationError) {
|
||||
this.validationError = undefined
|
||||
this.requestUpdate('_validationError')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the configuration.
|
||||
* @param event event
|
||||
*/
|
||||
public readonly saveConfig = async (event?: Event): Promise<void> => {
|
||||
event?.preventDefault()
|
||||
if (!this.firewallConfiguration || !this._adminFirewallService) {
|
||||
return
|
||||
}
|
||||
this.actionDisabled = true
|
||||
this._adminFirewallService.saveConfiguration(this.firewallConfiguration)
|
||||
.then((result: AdminFirewallConfiguration) => {
|
||||
this.validationError = undefined
|
||||
this.ptTranslate(LOC_SUCCESSFULLY_SAVED).then((msg) => {
|
||||
this.ptNotifier.info(msg)
|
||||
}, () => {})
|
||||
this.firewallConfiguration = result
|
||||
this.requestUpdate('firewallConfiguration')
|
||||
this.requestUpdate('_validationError')
|
||||
})
|
||||
.catch(async (error: Error) => {
|
||||
this.validationError = undefined
|
||||
if (error instanceof ValidationError) {
|
||||
this.validationError = error
|
||||
}
|
||||
this.logger.warn(`A validation error occurred in saving configuration. ${error.name}: ${error.message}`)
|
||||
this.ptNotifier.error(
|
||||
error.message
|
||||
? error.message
|
||||
: await this.ptTranslate(LOC_ERROR)
|
||||
)
|
||||
this.requestUpdate('_validationError')
|
||||
})
|
||||
.finally(() => {
|
||||
this.actionDisabled = false
|
||||
})
|
||||
}
|
||||
|
||||
public readonly getInputValidationClass = (propertyName: string): { [key: string]: boolean } => {
|
||||
const validationErrorTypes: ValidationErrorType[] | undefined =
|
||||
this.validationError?.properties[`${propertyName}`]
|
||||
return validationErrorTypes ? (validationErrorTypes.length ? { 'is-invalid': true } : { 'is-valid': true }) : {}
|
||||
}
|
||||
|
||||
public readonly renderFeedback = (feedbackId: string,
|
||||
propertyName: string): TemplateResult | typeof nothing => {
|
||||
const errorMessages: TemplateResult[] = []
|
||||
const validationErrorTypes: ValidationErrorType[] | undefined =
|
||||
this.validationError?.properties[`${propertyName}`] ?? undefined
|
||||
|
||||
// FIXME: this code is duplicated in dymamic table form
|
||||
if (validationErrorTypes && validationErrorTypes.length !== 0) {
|
||||
return html`<div id=${feedbackId} class="invalid-feedback">${errorMessages}</div>`
|
||||
} else {
|
||||
return nothing
|
||||
}
|
||||
}
|
||||
|
||||
protected override render = (): unknown => {
|
||||
return this._asyncTaskRender.render({
|
||||
pending: () => html`<livechat-spinner></livechat-spinner>`,
|
||||
error: () => html`<livechat-error></livechat-error>`,
|
||||
complete: () => tplAdminFirewall(this)
|
||||
})
|
||||
}
|
||||
}
|
5
client/common/admin/firewall/elements/index.ts
Normal file
5
client/common/admin/firewall/elements/index.ts
Normal file
@ -0,0 +1,5 @@
|
||||
// SPDX-FileCopyrightText: 2024 John Livingston <https://www.john-livingston.fr/>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
import './admin-firewall'
|
26
client/common/admin/firewall/register.ts
Normal file
26
client/common/admin/firewall/register.ts
Normal file
@ -0,0 +1,26 @@
|
||||
// SPDX-FileCopyrightText: 2024 John Livingston <https://www.john-livingston.fr/>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
import type { RegisterClientOptions } from '@peertube/peertube-types/client'
|
||||
import { html, render } from 'lit'
|
||||
import './elements' // Import all needed elements.
|
||||
|
||||
/**
|
||||
* Registers stuff related to mod_firewall configuration.
|
||||
* @param clientOptions Peertube client options
|
||||
*/
|
||||
async function registerAdminFirewall (clientOptions: RegisterClientOptions): Promise<void> {
|
||||
const { registerClientRoute } = clientOptions
|
||||
|
||||
registerClientRoute({
|
||||
route: 'livechat/admin/firewall',
|
||||
onMount: async ({ rootEl }) => {
|
||||
render(html`<livechat-admin-firewall .registerClientOptions=${clientOptions}></livechat-admin-firewall>`, rootEl)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export {
|
||||
registerAdminFirewall
|
||||
}
|
108
client/common/admin/firewall/services/admin-firewall.ts
Normal file
108
client/common/admin/firewall/services/admin-firewall.ts
Normal file
@ -0,0 +1,108 @@
|
||||
// SPDX-FileCopyrightText: 2024 John Livingston <https://www.john-livingston.fr/>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
import type { RegisterClientOptions } from '@peertube/peertube-types/client'
|
||||
import type { AdminFirewallConfiguration } from 'shared/lib/types'
|
||||
import {
|
||||
maxFirewallFileSize, maxFirewallNameLength, maxFirewallFiles, firewallNameRegexp
|
||||
} from 'shared/lib/admin-firewall'
|
||||
import { ValidationError, ValidationErrorType } from '../../../lib/models/validation'
|
||||
import { getBaseRoute } from '../../../../utils/uri'
|
||||
|
||||
export class AdminFirewallService {
|
||||
public _registerClientOptions: RegisterClientOptions
|
||||
|
||||
private readonly _headers: any = {}
|
||||
|
||||
constructor (registerClientOptions: RegisterClientOptions) {
|
||||
this._registerClientOptions = registerClientOptions
|
||||
|
||||
this._headers = this._registerClientOptions.peertubeHelpers.getAuthHeader() ?? {}
|
||||
this._headers['content-type'] = 'application/json;charset=UTF-8'
|
||||
}
|
||||
|
||||
async validateConfiguration (adminFirewallConfiguration: AdminFirewallConfiguration): Promise<boolean> {
|
||||
const propertiesError: ValidationError['properties'] = {}
|
||||
|
||||
if (adminFirewallConfiguration.files.length > maxFirewallFiles) {
|
||||
const validationError = new ValidationError(
|
||||
'AdminFirewallConfigurationValidationError',
|
||||
await this._registerClientOptions.peertubeHelpers.translate(LOC_TOO_MANY_ENTRIES),
|
||||
propertiesError
|
||||
)
|
||||
throw validationError
|
||||
}
|
||||
|
||||
const seen = new Map<string, true>()
|
||||
for (const [i, e] of adminFirewallConfiguration.files.entries()) {
|
||||
propertiesError[`files.${i}.name`] = []
|
||||
if (e.name === '') {
|
||||
propertiesError[`files.${i}.name`].push(ValidationErrorType.Missing)
|
||||
} else if (e.name.length > maxFirewallNameLength) {
|
||||
propertiesError[`files.${i}.name`].push(ValidationErrorType.TooLong)
|
||||
} else if (!firewallNameRegexp.test(e.name)) {
|
||||
propertiesError[`files.${i}.name`].push(ValidationErrorType.WrongFormat)
|
||||
} else if (seen.has(e.name)) {
|
||||
propertiesError[`files.${i}.name`].push(ValidationErrorType.Duplicate)
|
||||
} else {
|
||||
seen.set(e.name, true)
|
||||
}
|
||||
|
||||
propertiesError[`files.${i}.content`] = []
|
||||
if (e.content.length > maxFirewallFileSize) {
|
||||
propertiesError[`files.${i}.content`].push(ValidationErrorType.TooLong)
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.values(propertiesError).find(e => e.length > 0)) {
|
||||
const validationError = new ValidationError(
|
||||
'AdminFirewallConfigurationValidationError',
|
||||
await this._registerClientOptions.peertubeHelpers.translate(LOC_VALIDATION_ERROR),
|
||||
propertiesError
|
||||
)
|
||||
throw validationError
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
async saveConfiguration (
|
||||
adminFirewallConfiguration: AdminFirewallConfiguration
|
||||
): Promise<AdminFirewallConfiguration> {
|
||||
if (!await this.validateConfiguration(adminFirewallConfiguration)) {
|
||||
throw new Error('Invalid form data')
|
||||
}
|
||||
|
||||
const response = await fetch(
|
||||
getBaseRoute(this._registerClientOptions) + '/api/admin/firewall/',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: this._headers,
|
||||
body: JSON.stringify(adminFirewallConfiguration)
|
||||
}
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to save configuration.')
|
||||
}
|
||||
|
||||
return response.json()
|
||||
}
|
||||
|
||||
async fetchConfiguration (): Promise<AdminFirewallConfiguration> {
|
||||
const response = await fetch(
|
||||
getBaseRoute(this._registerClientOptions) + '/api/admin/firewall/',
|
||||
{
|
||||
method: 'GET',
|
||||
headers: this._headers
|
||||
}
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Can\'t get firewall configuration.')
|
||||
}
|
||||
|
||||
return response.json()
|
||||
}
|
||||
}
|
88
client/common/admin/firewall/templates/admin-firewall.ts
Normal file
88
client/common/admin/firewall/templates/admin-firewall.ts
Normal file
@ -0,0 +1,88 @@
|
||||
// SPDX-FileCopyrightText: 2024 John Livingston <https://www.john-livingston.fr/>
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
import type { AdminFirewallElement } from '../elements/admin-firewall'
|
||||
import type { TemplateResult } from 'lit'
|
||||
import type { DynamicFormHeader, DynamicFormSchema } from '../../../lib/elements/dynamic-table-form'
|
||||
import { maxFirewallFiles, maxFirewallNameLength, maxFirewallFileSize } from 'shared/lib/admin-firewall'
|
||||
import { ptTr } from '../../../lib/directives/translation'
|
||||
import { html } from 'lit'
|
||||
|
||||
export function tplAdminFirewall (el: AdminFirewallElement): TemplateResult {
|
||||
const tableHeaderList: DynamicFormHeader = {
|
||||
enabled: {
|
||||
colName: ptTr(LOC_PROSODY_FIREWALL_FILE_ENABLED)
|
||||
},
|
||||
name: {
|
||||
colName: ptTr(LOC_PROSODY_FIREWALL_NAME),
|
||||
description: ptTr(LOC_PROSODY_FIREWALL_NAME_DESC),
|
||||
headerClassList: ['peertube-livechat-admin-firewall-col-name']
|
||||
},
|
||||
content: {
|
||||
colName: ptTr(LOC_PROSODY_FIREWALL_CONTENT),
|
||||
headerClassList: ['peertube-livechat-admin-firewall-col-content']
|
||||
}
|
||||
}
|
||||
const tableSchema: DynamicFormSchema = {
|
||||
enabled: {
|
||||
inputType: 'checkbox',
|
||||
default: true
|
||||
},
|
||||
name: {
|
||||
inputType: 'text',
|
||||
default: '',
|
||||
maxlength: maxFirewallNameLength
|
||||
},
|
||||
content: {
|
||||
inputType: 'textarea',
|
||||
default: '',
|
||||
maxlength: maxFirewallFileSize
|
||||
}
|
||||
}
|
||||
|
||||
return html`
|
||||
<div class="margin-content peertube-plugin-livechat-admin-firewall">
|
||||
<h1>
|
||||
${ptTr(LOC_PROSODY_FIREWALL_CONFIGURATION)}
|
||||
</h1>
|
||||
<p>
|
||||
${ptTr(LOC_PROSODY_FIREWALL_CONFIGURATION_HELP, true)}
|
||||
<livechat-help-button .page=${'documentation/admin/mod_firewall'}>
|
||||
</livechat-help-button>
|
||||
</p>
|
||||
${
|
||||
el.firewallConfiguration?.enabled
|
||||
? ''
|
||||
: html`<p class="peertube-plugin-livechat-warning">${ptTr(LOC_PROSODY_FIREWALL_DISABLED_WARNING, true)}</p>`
|
||||
}
|
||||
|
||||
<form role="form" @submit=${el.saveConfig} @change=${el.resetValidation}>
|
||||
<livechat-dynamic-table-form
|
||||
.header=${tableHeaderList}
|
||||
.schema=${tableSchema}
|
||||
.maxLines=${maxFirewallFiles}
|
||||
.validation=${el.validationError?.properties}
|
||||
.validationPrefix=${'files'}
|
||||
.rows=${el.firewallConfiguration?.files}
|
||||
@update=${(e: CustomEvent) => {
|
||||
el.resetValidation(e)
|
||||
if (el.firewallConfiguration) {
|
||||
el.firewallConfiguration.files = e.detail
|
||||
el.requestUpdate('firewallConfiguration')
|
||||
}
|
||||
}
|
||||
}
|
||||
></livechat-dynamic-table-form>
|
||||
|
||||
<div class="form-group mt-5">
|
||||
<button type="reset" @click=${el.reset} ?disabled=${el.actionDisabled}>
|
||||
${ptTr(LOC_CANCEL)}
|
||||
</button>
|
||||
<button type="submit" ?disabled=${el.actionDisabled}>
|
||||
${ptTr(LOC_SAVE)}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>`
|
||||
}
|
@ -64,7 +64,7 @@ interface DynamicTableRowData {
|
||||
|
||||
interface DynamicFormHeaderCellData {
|
||||
colName: TemplateResult | DirectiveResult
|
||||
description: TemplateResult | DirectiveResult
|
||||
description?: TemplateResult | DirectiveResult
|
||||
headerClassList?: string[]
|
||||
}
|
||||
|
||||
@ -236,7 +236,7 @@ export class DynamicTableFormElement extends LivechatElement {
|
||||
classList.push(...headerCellData.headerClassList)
|
||||
}
|
||||
return html`<th scope="col" class=${classList.join(' ')}>
|
||||
${headerCellData.description}
|
||||
${headerCellData.description ?? ''}
|
||||
</th>`
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user