plugin-manager.ts 18 KB

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