]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/plugins/plugin-manager.ts
Prevent crash on plugin ws error
[github/Chocobozzz/PeerTube.git] / server / lib / plugins / plugin-manager.ts
1 import express from 'express'
2 import { createReadStream, createWriteStream } from 'fs'
3 import { ensureDir, outputFile, readJSON } from 'fs-extra'
4 import { Server } from 'http'
5 import { basename, join } from 'path'
6 import { decachePlugin } from '@server/helpers/decache'
7 import { ApplicationModel } from '@server/models/application/application'
8 import { MOAuthTokenUser, MUser } from '@server/types/models'
9 import { getCompleteLocale } from '@shared/core-utils'
10 import {
11 ClientScriptJSON,
12 PluginPackageJSON,
13 PluginTranslation,
14 PluginTranslationPathsJSON,
15 RegisterServerHookOptions
16 } from '@shared/models'
17 import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks'
18 import { PluginType } from '../../../shared/models/plugins/plugin.type'
19 import { ServerHook, ServerHookName } from '../../../shared/models/plugins/server/server-hook.model'
20 import { isLibraryCodeValid, isPackageJSONValid } from '../../helpers/custom-validators/plugins'
21 import { logger } from '../../helpers/logger'
22 import { CONFIG } from '../../initializers/config'
23 import { PLUGIN_GLOBAL_CSS_PATH } from '../../initializers/constants'
24 import { PluginModel } from '../../models/server/plugin'
25 import { PluginLibrary, RegisterServerAuthExternalOptions, RegisterServerAuthPassOptions, RegisterServerOptions } from '../../types/plugins'
26 import { ClientHtml } from '../client-html'
27 import { RegisterHelpers } from './register-helpers'
28 import { installNpmPlugin, installNpmPluginFromDisk, rebuildNativePlugins, removeNpmPlugin } from './yarn'
29
30 export interface RegisteredPlugin {
31 npmName: string
32 name: string
33 version: string
34 description: string
35 peertubeEngine: string
36
37 type: PluginType
38
39 path: string
40
41 staticDirs: { [name: string]: string }
42 clientScripts: { [name: string]: ClientScriptJSON }
43
44 css: string[]
45
46 // Only if this is a plugin
47 registerHelpers?: RegisterHelpers
48 unregister?: Function
49 }
50
51 export interface HookInformationValue {
52 npmName: string
53 pluginName: string
54 handler: Function
55 priority: number
56 }
57
58 type PluginLocalesTranslations = {
59 [locale: string]: PluginTranslation
60 }
61
62 export class PluginManager implements ServerHook {
63
64 private static instance: PluginManager
65
66 private registeredPlugins: { [name: string]: RegisteredPlugin } = {}
67
68 private hooks: { [name: string]: HookInformationValue[] } = {}
69 private translations: PluginLocalesTranslations = {}
70
71 private server: Server
72
73 private constructor () {
74 }
75
76 init (server: Server) {
77 this.server = server
78 }
79
80 registerWebSocketRouter () {
81 this.server.on('upgrade', (request, socket, head) => {
82 // Check if it's a plugin websocket connection
83 // No need to destroy the stream when we abort the request
84 // Other handlers in PeerTube will catch this upgrade event too (socket.io, tracker etc)
85
86 const url = request.url
87
88 const matched = url.match(`/plugins/([^/]+)/([^/]+/)?ws(/.*)`)
89 if (!matched) return
90
91 const npmName = PluginModel.buildNpmName(matched[1], PluginType.PLUGIN)
92 const subRoute = matched[3]
93
94 const result = this.getRegisteredPluginOrTheme(npmName)
95 if (!result) return
96
97 const routes = result.registerHelpers.getWebSocketRoutes()
98
99 const wss = routes.find(r => r.route.startsWith(subRoute))
100 if (!wss) return
101
102 try {
103 wss.handler(request, socket, head)
104 } catch (err) {
105 logger.error('Exception in plugin handler ' + npmName, { err })
106 }
107 })
108 }
109
110 // ###################### Getters ######################
111
112 isRegistered (npmName: string) {
113 return !!this.getRegisteredPluginOrTheme(npmName)
114 }
115
116 getRegisteredPluginOrTheme (npmName: string) {
117 return this.registeredPlugins[npmName]
118 }
119
120 getRegisteredPluginByShortName (name: string) {
121 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
122 const registered = this.getRegisteredPluginOrTheme(npmName)
123
124 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
125
126 return registered
127 }
128
129 getRegisteredThemeByShortName (name: string) {
130 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
131 const registered = this.getRegisteredPluginOrTheme(npmName)
132
133 if (!registered || registered.type !== PluginType.THEME) return undefined
134
135 return registered
136 }
137
138 getRegisteredPlugins () {
139 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
140 }
141
142 getRegisteredThemes () {
143 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
144 }
145
146 getIdAndPassAuths () {
147 return this.getRegisteredPlugins()
148 .map(p => ({
149 npmName: p.npmName,
150 name: p.name,
151 version: p.version,
152 idAndPassAuths: p.registerHelpers.getIdAndPassAuths()
153 }))
154 .filter(v => v.idAndPassAuths.length !== 0)
155 }
156
157 getExternalAuths () {
158 return this.getRegisteredPlugins()
159 .map(p => ({
160 npmName: p.npmName,
161 name: p.name,
162 version: p.version,
163 externalAuths: p.registerHelpers.getExternalAuths()
164 }))
165 .filter(v => v.externalAuths.length !== 0)
166 }
167
168 getRegisteredSettings (npmName: string) {
169 const result = this.getRegisteredPluginOrTheme(npmName)
170 if (!result || result.type !== PluginType.PLUGIN) return []
171
172 return result.registerHelpers.getSettings()
173 }
174
175 getRouter (npmName: string) {
176 const result = this.getRegisteredPluginOrTheme(npmName)
177 if (!result || result.type !== PluginType.PLUGIN) return null
178
179 return result.registerHelpers.getRouter()
180 }
181
182 getTranslations (locale: string) {
183 return this.translations[locale] || {}
184 }
185
186 async isTokenValid (token: MOAuthTokenUser, type: 'access' | 'refresh') {
187 const auth = this.getAuth(token.User.pluginAuth, token.authName)
188 if (!auth) return true
189
190 if (auth.hookTokenValidity) {
191 try {
192 const { valid } = await auth.hookTokenValidity({ token, type })
193
194 if (valid === false) {
195 logger.info('Rejecting %s token validity from auth %s of plugin %s', type, token.authName, token.User.pluginAuth)
196 }
197
198 return valid
199 } catch (err) {
200 logger.warn('Cannot run check token validity from auth %s of plugin %s.', token.authName, token.User.pluginAuth, { err })
201 return true
202 }
203 }
204
205 return true
206 }
207
208 // ###################### External events ######################
209
210 async onLogout (npmName: string, authName: string, user: MUser, req: express.Request) {
211 const auth = this.getAuth(npmName, authName)
212
213 if (auth?.onLogout) {
214 logger.info('Running onLogout function from auth %s of plugin %s', authName, npmName)
215
216 try {
217 // Force await, in case or onLogout returns a promise
218 const result = await auth.onLogout(user, req)
219
220 return typeof result === 'string'
221 ? result
222 : undefined
223 } catch (err) {
224 logger.warn('Cannot run onLogout function from auth %s of plugin %s.', authName, npmName, { err })
225 }
226 }
227
228 return undefined
229 }
230
231 async onSettingsChanged (name: string, settings: any) {
232 const registered = this.getRegisteredPluginByShortName(name)
233 if (!registered) {
234 logger.error('Cannot find plugin %s to call on settings changed.', name)
235 }
236
237 for (const cb of registered.registerHelpers.getOnSettingsChangedCallbacks()) {
238 try {
239 await cb(settings)
240 } catch (err) {
241 logger.error('Cannot run on settings changed callback for %s.', registered.npmName, { err })
242 }
243 }
244 }
245
246 // ###################### Hooks ######################
247
248 async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
249 if (!this.hooks[hookName]) return Promise.resolve(result)
250
251 const hookType = getHookType(hookName)
252
253 for (const hook of this.hooks[hookName]) {
254 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
255
256 result = await internalRunHook({
257 handler: hook.handler,
258 hookType,
259 result,
260 params,
261 onError: err => { logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err }) }
262 })
263 }
264
265 return result
266 }
267
268 // ###################### Registration ######################
269
270 async registerPluginsAndThemes () {
271 await this.resetCSSGlobalFile()
272
273 const plugins = await PluginModel.listEnabledPluginsAndThemes()
274
275 for (const plugin of plugins) {
276 try {
277 await this.registerPluginOrTheme(plugin)
278 } catch (err) {
279 // Try to unregister the plugin
280 try {
281 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
282 } catch {
283 // we don't care if we cannot unregister it
284 }
285
286 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
287 }
288 }
289
290 this.sortHooksByPriority()
291 }
292
293 // Don't need the plugin type since themes cannot register server code
294 async unregister (npmName: string) {
295 logger.info('Unregister plugin %s.', npmName)
296
297 const plugin = this.getRegisteredPluginOrTheme(npmName)
298
299 if (!plugin) {
300 throw new Error(`Unknown plugin ${npmName} to unregister`)
301 }
302
303 delete this.registeredPlugins[plugin.npmName]
304
305 this.deleteTranslations(plugin.npmName)
306
307 if (plugin.type === PluginType.PLUGIN) {
308 await plugin.unregister()
309
310 // Remove hooks of this plugin
311 for (const key of Object.keys(this.hooks)) {
312 this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName)
313 }
314
315 const store = plugin.registerHelpers
316 store.reinitVideoConstants(plugin.npmName)
317 store.reinitTranscodingProfilesAndEncoders(plugin.npmName)
318
319 logger.info('Regenerating registered plugin CSS to global file.')
320 await this.regeneratePluginGlobalCSS()
321 }
322
323 ClientHtml.invalidCache()
324 }
325
326 // ###################### Installation ######################
327
328 async install (toInstall: string, version?: string, fromDisk = false) {
329 let plugin: PluginModel
330 let npmName: string
331
332 logger.info('Installing plugin %s.', toInstall)
333
334 try {
335 fromDisk
336 ? await installNpmPluginFromDisk(toInstall)
337 : await installNpmPlugin(toInstall, version)
338
339 npmName = fromDisk ? basename(toInstall) : toInstall
340 const pluginType = PluginModel.getTypeFromNpmName(npmName)
341 const pluginName = PluginModel.normalizePluginName(npmName)
342
343 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
344
345 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
346
347 [ plugin ] = await PluginModel.upsert({
348 name: pluginName,
349 description: packageJSON.description,
350 homepage: packageJSON.homepage,
351 type: pluginType,
352 version: packageJSON.version,
353 enabled: true,
354 uninstalled: false,
355 peertubeEngine: packageJSON.engine.peertube
356 }, { returning: true })
357
358 logger.info('Successful installation of plugin %s.', toInstall)
359
360 await this.registerPluginOrTheme(plugin)
361 } catch (rootErr) {
362 logger.error('Cannot install plugin %s, removing it...', toInstall, { err: rootErr })
363
364 try {
365 await this.uninstall(npmName)
366 } catch (err) {
367 logger.error('Cannot uninstall plugin %s after failed installation.', toInstall, { err })
368
369 try {
370 await removeNpmPlugin(npmName)
371 } catch (err) {
372 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
373 }
374 }
375
376 throw rootErr
377 }
378
379 return plugin
380 }
381
382 async update (toUpdate: string, fromDisk = false) {
383 const npmName = fromDisk ? basename(toUpdate) : toUpdate
384
385 logger.info('Updating plugin %s.', npmName)
386
387 // Use the latest version from DB, to not upgrade to a version that does not support our PeerTube version
388 let version: string
389 if (!fromDisk) {
390 const plugin = await PluginModel.loadByNpmName(toUpdate)
391 version = plugin.latestVersion
392 }
393
394 // Unregister old hooks
395 await this.unregister(npmName)
396
397 return this.install(toUpdate, version, fromDisk)
398 }
399
400 async uninstall (npmName: string) {
401 logger.info('Uninstalling plugin %s.', npmName)
402
403 try {
404 await this.unregister(npmName)
405 } catch (err) {
406 logger.warn('Cannot unregister plugin %s.', npmName, { err })
407 }
408
409 const plugin = await PluginModel.loadByNpmName(npmName)
410 if (!plugin || plugin.uninstalled === true) {
411 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
412 return
413 }
414
415 plugin.enabled = false
416 plugin.uninstalled = true
417
418 await plugin.save()
419
420 await removeNpmPlugin(npmName)
421
422 logger.info('Plugin %s uninstalled.', npmName)
423 }
424
425 async rebuildNativePluginsIfNeeded () {
426 if (!await ApplicationModel.nodeABIChanged()) return
427
428 return rebuildNativePlugins()
429 }
430
431 // ###################### Private register ######################
432
433 private async registerPluginOrTheme (plugin: PluginModel) {
434 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
435
436 logger.info('Registering plugin or theme %s.', npmName)
437
438 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
439 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
440
441 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
442
443 let library: PluginLibrary
444 let registerHelpers: RegisterHelpers
445 if (plugin.type === PluginType.PLUGIN) {
446 const result = await this.registerPlugin(plugin, pluginPath, packageJSON)
447 library = result.library
448 registerHelpers = result.registerStore
449 }
450
451 const clientScripts: { [id: string]: ClientScriptJSON } = {}
452 for (const c of packageJSON.clientScripts) {
453 clientScripts[c.script] = c
454 }
455
456 this.registeredPlugins[npmName] = {
457 npmName,
458 name: plugin.name,
459 type: plugin.type,
460 version: plugin.version,
461 description: plugin.description,
462 peertubeEngine: plugin.peertubeEngine,
463 path: pluginPath,
464 staticDirs: packageJSON.staticDirs,
465 clientScripts,
466 css: packageJSON.css,
467 registerHelpers: registerHelpers || undefined,
468 unregister: library ? library.unregister : undefined
469 }
470
471 await this.addTranslations(plugin, npmName, packageJSON.translations)
472
473 ClientHtml.invalidCache()
474 }
475
476 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJSON) {
477 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
478
479 // Delete cache if needed
480 const modulePath = join(pluginPath, packageJSON.library)
481 decachePlugin(pluginPath, modulePath)
482 const library: PluginLibrary = require(modulePath)
483
484 if (!isLibraryCodeValid(library)) {
485 throw new Error('Library code is not valid (miss register or unregister function)')
486 }
487
488 const { registerOptions, registerStore } = this.getRegisterHelpers(npmName, plugin)
489
490 await ensureDir(registerOptions.peertubeHelpers.plugin.getDataDirectoryPath())
491
492 await library.register(registerOptions)
493
494 logger.info('Add plugin %s CSS to global file.', npmName)
495
496 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
497
498 return { library, registerStore }
499 }
500
501 // ###################### Translations ######################
502
503 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PluginTranslationPathsJSON) {
504 for (const locale of Object.keys(translationPaths)) {
505 const path = translationPaths[locale]
506 const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
507
508 const completeLocale = getCompleteLocale(locale)
509
510 if (!this.translations[completeLocale]) this.translations[completeLocale] = {}
511 this.translations[completeLocale][npmName] = json
512
513 logger.info('Added locale %s of plugin %s.', completeLocale, npmName)
514 }
515 }
516
517 private deleteTranslations (npmName: string) {
518 for (const locale of Object.keys(this.translations)) {
519 delete this.translations[locale][npmName]
520
521 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
522 }
523 }
524
525 // ###################### CSS ######################
526
527 private resetCSSGlobalFile () {
528 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
529 }
530
531 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
532 for (const cssPath of cssRelativePaths) {
533 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
534 }
535 }
536
537 private concatFiles (input: string, output: string) {
538 return new Promise<void>((res, rej) => {
539 const inputStream = createReadStream(input)
540 const outputStream = createWriteStream(output, { flags: 'a' })
541
542 inputStream.pipe(outputStream)
543
544 inputStream.on('end', () => res())
545 inputStream.on('error', err => rej(err))
546 })
547 }
548
549 private async regeneratePluginGlobalCSS () {
550 await this.resetCSSGlobalFile()
551
552 for (const plugin of this.getRegisteredPlugins()) {
553 await this.addCSSToGlobalFile(plugin.path, plugin.css)
554 }
555 }
556
557 // ###################### Utils ######################
558
559 private sortHooksByPriority () {
560 for (const hookName of Object.keys(this.hooks)) {
561 this.hooks[hookName].sort((a, b) => {
562 return b.priority - a.priority
563 })
564 }
565 }
566
567 private getPackageJSON (pluginName: string, pluginType: PluginType) {
568 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
569
570 return readJSON(pluginPath) as Promise<PluginPackageJSON>
571 }
572
573 private getPluginPath (pluginName: string, pluginType: PluginType) {
574 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
575
576 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
577 }
578
579 private getAuth (npmName: string, authName: string) {
580 const plugin = this.getRegisteredPluginOrTheme(npmName)
581 if (!plugin || plugin.type !== PluginType.PLUGIN) return null
582
583 let auths: (RegisterServerAuthPassOptions | RegisterServerAuthExternalOptions)[] = plugin.registerHelpers.getIdAndPassAuths()
584 auths = auths.concat(plugin.registerHelpers.getExternalAuths())
585
586 return auths.find(a => a.authName === authName)
587 }
588
589 // ###################### Private getters ######################
590
591 private getRegisteredPluginsOrThemes (type: PluginType) {
592 const plugins: RegisteredPlugin[] = []
593
594 for (const npmName of Object.keys(this.registeredPlugins)) {
595 const plugin = this.registeredPlugins[npmName]
596 if (plugin.type !== type) continue
597
598 plugins.push(plugin)
599 }
600
601 return plugins
602 }
603
604 // ###################### Generate register helpers ######################
605
606 private getRegisterHelpers (
607 npmName: string,
608 plugin: PluginModel
609 ): { registerStore: RegisterHelpers, registerOptions: RegisterServerOptions } {
610 const onHookAdded = (options: RegisterServerHookOptions) => {
611 if (!this.hooks[options.target]) this.hooks[options.target] = []
612
613 this.hooks[options.target].push({
614 npmName,
615 pluginName: plugin.name,
616 handler: options.handler,
617 priority: options.priority || 0
618 })
619 }
620
621 const registerHelpers = new RegisterHelpers(npmName, plugin, this.server, onHookAdded.bind(this))
622
623 return {
624 registerStore: registerHelpers,
625 registerOptions: registerHelpers.buildRegisterHelpers()
626 }
627 }
628
629 private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJSON, pluginType: PluginType) {
630 if (!packageJSON.staticDirs) packageJSON.staticDirs = {}
631 if (!packageJSON.css) packageJSON.css = []
632 if (!packageJSON.clientScripts) packageJSON.clientScripts = []
633 if (!packageJSON.translations) packageJSON.translations = {}
634
635 const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
636 if (!packageJSONValid) {
637 const formattedFields = badFields.map(f => `"${f}"`)
638 .join(', ')
639
640 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
641 }
642 }
643
644 static get Instance () {
645 return this.instance || (this.instance = new this())
646 }
647 }