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