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