import type { RegisterServerOptions, MVideoThumbnail } from '@peertube/peertube-types' import type { Router, Request, Response, NextFunction } from 'express' import type { ProsodyListRoomsResult, ProsodyListRoomsResultRoom } from '../../../shared/lib/types' import { createProxyServer } from 'http-proxy' import { getBaseRouterRoute, getBaseRouterCanonicalRoute, getBaseStaticRoute, isUserAdmin } from '../helpers' import { asyncMiddleware } from '../middlewares/async' import { getProsodyDomain } from '../prosody/config/domain' import { getAPIKey } from '../apikey' import { getChannelInfosById, getChannelNameById } from '../database/channel' import { isAutoColorsAvailable, areAutoColorsValid, AutoColors } from '../../../shared/lib/autocolors' import * as path from 'path' const got = require('got') const fs = require('fs').promises // const proxy = require('express-http-proxy') interface ProsodyProxyInfo { host: string port: string } let currentProsodyProxyInfo: ProsodyProxyInfo | null = null let currentHttpBindProxy: ReturnType | null = null async function initWebchatRouter (options: RegisterServerOptions): Promise { const { getRouter, peertubeHelpers, settingsManager } = options const converseJSIndex = await fs.readFile(path.resolve(__dirname, '../../conversejs/index.html')) const router: Router = getRouter() // eslint-disable-next-line @typescript-eslint/no-misused-promises router.get('/room/:roomKey', asyncMiddleware( async (req: Request, res: Response, _next: NextFunction): Promise => { res.removeHeader('X-Frame-Options') // this route can be opened in an iframe const roomKey = req.params.roomKey const settings = await settingsManager.getSettings([ 'prosody-room-type', 'converse-theme', 'converse-autocolors' ]) let room: string let authenticationUrl: string = '' let advancedControls: boolean = false // auto join the chat in viewer mode, if not logged in let autoViewerMode: boolean = false let forceReadonly: 'true' | 'false' | 'noscroll' = 'false' let converseJSTheme: string = settings['converse-theme'] as string let transparent: boolean = false if (!/^\w+$/.test(converseJSTheme)) { converseJSTheme = 'peertube' } const prosodyDomain = await getProsodyDomain(options) const jid = 'anon.' + prosodyDomain if (req.query.forcetype === '1') { // We come from the room list in the settings page. // Here we don't read the prosody-room-type settings, // but use the roomKey format. // NB: there is no extra security. Any user can add this parameter. // This is not an issue: the setting will be tested at the room creation. // No room can be created in the wrong mode. if (/^channel\.\d+$/.test(roomKey)) { room = 'channel.{{CHANNEL_ID}}@room.' + prosodyDomain } else { room = '{{VIDEO_UUID}}@room.' + prosodyDomain } } else { if (settings['prosody-room-type'] === 'channel') { room = 'channel.{{CHANNEL_ID}}@room.' + prosodyDomain } else { room = '{{VIDEO_UUID}}@room.' + prosodyDomain } } // Here we are using getBaseRouterCanonicalRoute, // which correspond to a path without the plugin version. // We are doing this, so the path is predictible, // and can be optimized in the nginx configuration (to bypass Peertube). const boshUri = getBaseRouterCanonicalRoute(options) + 'webchat/http-bind' const wsUri = '' authenticationUrl = options.peertubeHelpers.config.getWebserverUrl() + getBaseRouterRoute(options) + 'api/auth' advancedControls = true if (req.query._readonly === 'true') { forceReadonly = 'true' } else if (req.query._readonly === 'noscroll') { forceReadonly = 'noscroll' } else { autoViewerMode = true // auto join the chat in viewer mode, if not logged in } if (req.query._transparent === 'true') { transparent = true } let video: MVideoThumbnail | undefined let channelId: number const channelMatches = roomKey.match(/^channel\.(\d+)$/) if (channelMatches?.[1]) { channelId = parseInt(channelMatches[1]) // Here we are on a channel room... const channelInfos = await getChannelInfosById(options, channelId) if (!channelInfos) { throw new Error('Channel not found') } channelId = channelInfos.id } else { const uuid = roomKey // must be a video UUID. video = await peertubeHelpers.videos.loadByIdOrUUID(uuid) if (!video) { throw new Error('Video not found') } channelId = video.channelId } let page = '' + (converseJSIndex as string) const baseStaticUrl = getBaseStaticRoute(options) page = page.replace(/{{BASE_STATIC_URL}}/g, baseStaticUrl) page = page.replace(/{{JID}}/g, jid) // Computing the room name... if (room.includes('{{VIDEO_UUID}}')) { if (!video) { throw new Error('Missing video') } room = room.replace(/{{VIDEO_UUID}}/g, video.uuid) } room = room.replace(/{{CHANNEL_ID}}/g, `${channelId}`) if (room.includes('{{CHANNEL_NAME}}')) { const channelName = await getChannelNameById(options, channelId) if (channelName === null) { throw new Error('Channel not found') } if (!/^[a-zA-Z0-9_.]+$/.test(channelName)) { // FIXME: see if there is a response here https://github.com/Chocobozzz/PeerTube/issues/4301 for allowed chars peertubeHelpers.logger.error(`Invalid channel name, contains unauthorized chars: '${channelName}'`) throw new Error('Invalid channel name, contains unauthorized chars') } room = room.replace(/{{CHANNEL_NAME}}/g, channelName) } let autocolorsStyles = '' if ( settings['converse-autocolors'] && isAutoColorsAvailable(settings['converse-theme'] as string) ) { peertubeHelpers.logger.debug('Trying to load AutoColors...') const autocolors: AutoColors = { mainForeground: req.query._ac_mainForeground?.toString() ?? '', mainBackground: req.query._ac_mainBackground?.toString() ?? '', greyForeground: req.query._ac_greyForeground?.toString() ?? '', greyBackground: req.query._ac_greyBackground?.toString() ?? '', menuForeground: req.query._ac_menuForeground?.toString() ?? '', menuBackground: req.query._ac_menuBackground?.toString() ?? '', inputForeground: req.query._ac_inputForeground?.toString() ?? '', inputBackground: req.query._ac_inputBackground?.toString() ?? '', buttonForeground: req.query._ac_buttonForeground?.toString() ?? '', buttonBackground: req.query._ac_buttonBackground?.toString() ?? '', link: req.query._ac_link?.toString() ?? '', linkHover: req.query._ac_linkHover?.toString() ?? '' } const autoColorsTest = areAutoColorsValid(autocolors) if (autoColorsTest === true) { autocolorsStyles = ` ` } else { peertubeHelpers.logger.error('Provided AutoColors are invalid.', autoColorsTest) } } else { peertubeHelpers.logger.debug('No AutoColors.') } // ... then inject it in the page. page = page.replace(/{{ROOM}}/g, room) page = page.replace(/{{BOSH_SERVICE_URL}}/g, boshUri) page = page.replace(/{{WS_SERVICE_URL}}/g, wsUri) page = page.replace(/{{AUTHENTICATION_URL}}/g, authenticationUrl) page = page.replace(/{{ADVANCEDCONTROLS}}/g, advancedControls ? 'true' : 'false') page = page.replace(/{{AUTOVIEWERMODE}}/g, autoViewerMode ? 'true' : 'false') page = page.replace(/{{CONVERSEJS_THEME}}/g, converseJSTheme) page = page.replace(/{{CONVERSEJS_AUTOCOLORS}}/g, autocolorsStyles) page = page.replace(/{{FORCEREADONLY}}/g, forceReadonly) page = page.replace(/{{TRANSPARENT}}/g, transparent ? 'true' : 'false') res.status(200) res.type('html') res.send(page) } )) await disableProxyRoute(options) router.all('/http-bind', (req: Request, res: Response, next: NextFunction) => { try { if (!currentHttpBindProxy) { res.status(404) res.send('Not found') return } req.url = 'http-bind' currentHttpBindProxy.web(req, res) } catch (err) { next(err) } } ) router.get('/prosody-list-rooms', asyncMiddleware( async (req: Request, res: Response, _next: NextFunction) => { if (!res.locals.authenticated) { res.sendStatus(403) return } if (!await isUserAdmin(options, res)) { res.sendStatus(403) return } if (!currentProsodyProxyInfo) { throw new Error('It seems that prosody is not binded... Cant list rooms.') } const apiUrl = `http://localhost:${currentProsodyProxyInfo.port}/peertubelivechat_list_rooms/list-rooms` peertubeHelpers.logger.debug('Calling list rooms API on url: ' + apiUrl) const rooms = await got(apiUrl, { method: 'GET', headers: { authorization: 'Bearer ' + await getAPIKey(options), host: currentProsodyProxyInfo.host }, responseType: 'json', resolveBodyOnly: true }) if (Array.isArray(rooms)) { for (let i = 0; i < rooms.length; i++) { const room: ProsodyListRoomsResultRoom = rooms[i] const matches = room.localpart.match(/^channel\.(\d+)$/) if (matches?.[1]) { const channelId = parseInt(matches[1]) const channelInfos = await getChannelInfosById(options, channelId) if (channelInfos) { room.channel = { id: channelInfos.id, name: channelInfos.name, displayName: channelInfos.displayName } } } } } res.status(200) const r: ProsodyListRoomsResult = { ok: true, rooms: rooms } res.json(r) } )) return router } // function changeHttpBindRoute ( // { peertubeHelpers }: RegisterServerOptions, // prosodyHttpBindInfo: ProsodyHttpBindInfo | null // ): void { // const logger = peertubeHelpers.logger // if (prosodyHttpBindInfo && !/^\d+$/.test(prosodyHttpBindInfo.port)) { // logger.error(`Port '${prosodyHttpBindInfo.port}' is not valid. Replacing by null`) // prosodyHttpBindInfo = null // } // if (!prosodyHttpBindInfo) { // logger.info('Changing http-bind port for null') // currentProsodyHttpBindInfo = null // httpBindRoute = (_req: Request, res: Response, _next: NextFunction) => { // res.status(404) // res.send('Not found') // } // } else { // logger.info('Changing http-bind port for ' + prosodyHttpBindInfo.port + ', on host ' + prosodyHttpBindInfo.host) // const options: ProxyOptions = { // https: false, // proxyReqPathResolver: async (_req: Request): Promise => { // return '/http-bind' // should not be able to access anything else // }, // // preserveHostHdr: true, // parseReqBody: true // Note that setting this to false overrides reqAsBuffer and reqBodyEncoding below. // // FIXME: should we remove cookies? // } // currentProsodyHttpBindInfo = prosodyHttpBindInfo // httpBindRoute = proxy('http://localhost:' + prosodyHttpBindInfo.port, options) // } // } async function disableProxyRoute ({ peertubeHelpers }: RegisterServerOptions): Promise { return new Promise((resolve) => { try { currentProsodyProxyInfo = null if (!currentHttpBindProxy) { resolve() return } peertubeHelpers.logger.debug('Closing the proxy...') currentHttpBindProxy.close(() => { peertubeHelpers.logger.debug('The proxy is closed.') resolve() }) currentHttpBindProxy = null } catch (err) { peertubeHelpers.logger.error('Seems that the http bind proxy close has failed: ' + (err as string)) resolve() } }) } async function enableProxyRoute ( { peertubeHelpers }: RegisterServerOptions, prosodyProxyInfo: ProsodyProxyInfo ): Promise { const logger = peertubeHelpers.logger if (!/^\d+$/.test(prosodyProxyInfo.port)) { logger.error(`Port '${prosodyProxyInfo.port}' is not valid. Aborting.`) return } currentProsodyProxyInfo = prosodyProxyInfo logger.debug('Creating a new http bind proxy') currentHttpBindProxy = createProxyServer({ target: 'http://localhost:' + prosodyProxyInfo.port + '/http-bind', ignorePath: true }) } export { initWebchatRouter, disableProxyRoute, enableProxyRoute }