growi-plugin.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. import fs, { readFileSync } from 'fs';
  2. import path from 'path';
  3. import { GrowiPluginType, GrowiThemeMetadata, ViteManifest } from '@growi/core';
  4. // eslint-disable-next-line no-restricted-imports
  5. import axios from 'axios';
  6. import mongoose from 'mongoose';
  7. import streamToPromise from 'stream-to-promise';
  8. import unzipper from 'unzipper';
  9. import loggerFactory from '~/utils/logger';
  10. import { resolveFromRoot } from '~/utils/project-dir-utils';
  11. import type {
  12. IGrowiPlugin, IGrowiPluginOrigin, IGrowiThemePluginMeta, IGrowiPluginMeta,
  13. } from '../../interfaces';
  14. import { GrowiPlugin } from '../models';
  15. import { GitHubUrl } from '../models/vo/github-url';
  16. const logger = loggerFactory('growi:plugins:plugin-utils');
  17. const pluginStoringPath = resolveFromRoot('tmp/plugins');
  18. const PLUGINS_STATIC_DIR = '/static/plugins'; // configured by express.static
  19. export type GrowiPluginResourceEntries = [installedPath: string, href: string][];
  20. function retrievePluginManifest(growiPlugin: IGrowiPlugin): ViteManifest {
  21. const manifestPath = resolveFromRoot(path.join('tmp/plugins', growiPlugin.installedPath, 'dist/manifest.json'));
  22. const manifestStr: string = readFileSync(manifestPath, 'utf-8');
  23. return JSON.parse(manifestStr);
  24. }
  25. type FindThemePluginResult = {
  26. growiPlugin: IGrowiPlugin,
  27. themeMetadata: GrowiThemeMetadata,
  28. themeHref: string,
  29. }
  30. export interface IGrowiPluginService {
  31. install(origin: IGrowiPluginOrigin): Promise<string>
  32. findThemePlugin(theme: string): Promise<FindThemePluginResult | null>
  33. retrieveAllPluginResourceEntries(): Promise<GrowiPluginResourceEntries>
  34. downloadNotExistPluginRepositories(): Promise<void>
  35. }
  36. export class GrowiPluginService implements IGrowiPluginService {
  37. /*
  38. * Downloading a non-existent repository to the file system
  39. */
  40. async downloadNotExistPluginRepositories(): Promise<void> {
  41. try {
  42. // find all growi plugin documents
  43. const growiPlugins = await GrowiPlugin.find({});
  44. // if not exists repository in file system, download latest plugin repository
  45. for await (const growiPlugin of growiPlugins) {
  46. const pluginPath = path.join(pluginStoringPath, growiPlugin.installedPath);
  47. const organizationName = path.join(pluginStoringPath, growiPlugin.organizationName);
  48. if (fs.existsSync(pluginPath)) {
  49. continue;
  50. }
  51. else {
  52. if (!fs.existsSync(organizationName)) {
  53. fs.mkdirSync(organizationName);
  54. }
  55. // TODO: imprv Document version and repository version possibly different.
  56. const ghUrl = new GitHubUrl(growiPlugin.origin.url, growiPlugin.origin.branchName);
  57. const { reposName, branchName, archiveUrl } = ghUrl;
  58. const zipFilePath = path.join(pluginStoringPath, `${branchName}.zip`);
  59. const unzippedPath = pluginStoringPath;
  60. const unzippedReposPath = path.join(pluginStoringPath, `${reposName}-${branchName}`);
  61. try {
  62. // download github repository to local file system
  63. await this.download(archiveUrl, zipFilePath);
  64. await this.unzip(zipFilePath, unzippedPath);
  65. fs.renameSync(unzippedReposPath, pluginPath);
  66. }
  67. catch (err) {
  68. // clean up, documents are not operated
  69. if (fs.existsSync(unzippedReposPath)) await fs.promises.rm(unzippedReposPath, { recursive: true });
  70. if (fs.existsSync(pluginPath)) await fs.promises.rm(pluginPath, { recursive: true });
  71. logger.error(err);
  72. }
  73. continue;
  74. }
  75. }
  76. }
  77. catch (err) {
  78. logger.error(err);
  79. }
  80. }
  81. /*
  82. * Install a plugin from URL and save it in the DB and file system.
  83. */
  84. async install(origin: IGrowiPluginOrigin): Promise<string> {
  85. const ghUrl = new GitHubUrl(origin.url, origin.ghBranch);
  86. const {
  87. organizationName, reposName, branchName, archiveUrl,
  88. } = ghUrl;
  89. const installedPath = `${organizationName}/${reposName}`;
  90. const zipFilePath = path.join(pluginStoringPath, `${branchName}.zip`);
  91. const unzippedPath = pluginStoringPath;
  92. const unzippedReposPath = path.join(pluginStoringPath, `${reposName}-${branchName}`);
  93. const temporaryReposPath = path.join(pluginStoringPath, reposName);
  94. const reposStoringPath = path.join(pluginStoringPath, `${installedPath}`);
  95. const organizationPath = path.join(pluginStoringPath, organizationName);
  96. let plugins: IGrowiPlugin<IGrowiPluginMeta>[];
  97. try {
  98. // download github repository to file system's temporary path
  99. await this.download(archiveUrl, zipFilePath);
  100. await this.unzip(zipFilePath, unzippedPath);
  101. fs.renameSync(unzippedReposPath, temporaryReposPath);
  102. // detect plugins
  103. plugins = await GrowiPluginService.detectPlugins(origin, organizationName, reposName);
  104. if (!fs.existsSync(organizationPath)) fs.mkdirSync(organizationPath);
  105. // remove the old repository from the storing path
  106. if (fs.existsSync(reposStoringPath)) await fs.promises.rm(reposStoringPath, { recursive: true });
  107. // move new repository from temporary path to storing path.
  108. fs.renameSync(temporaryReposPath, reposStoringPath);
  109. }
  110. catch (err) {
  111. // clean up
  112. if (fs.existsSync(zipFilePath)) await fs.promises.rm(zipFilePath);
  113. if (fs.existsSync(unzippedReposPath)) await fs.promises.rm(unzippedReposPath, { recursive: true });
  114. if (fs.existsSync(temporaryReposPath)) await fs.promises.rm(temporaryReposPath, { recursive: true });
  115. logger.error(err);
  116. throw err;
  117. }
  118. try {
  119. // delete plugin documents if these exist
  120. await this.deleteOldPluginDocument(installedPath);
  121. // save new plugins metadata
  122. await this.savePluginMetaData(plugins);
  123. return plugins[0].meta.name;
  124. }
  125. catch (err) {
  126. // clean up
  127. if (fs.existsSync(reposStoringPath)) await fs.promises.rm(reposStoringPath, { recursive: true });
  128. await this.deleteOldPluginDocument(installedPath);
  129. logger.error(err);
  130. throw err;
  131. }
  132. }
  133. private async deleteOldPluginDocument(path: string): Promise<void> {
  134. await GrowiPlugin.deleteMany({ installedPath: path });
  135. }
  136. // !! DO NOT USE WHERE NOT SSRF GUARDED !! -- 2022.12.26 ryoji-s
  137. private async download(requestUrl: string, filePath: string): Promise<void> {
  138. return new Promise<void>((resolve, rejects) => {
  139. axios({
  140. method: 'GET',
  141. url: requestUrl,
  142. responseType: 'stream',
  143. })
  144. .then((res) => {
  145. if (res.status === 200) {
  146. const file = fs.createWriteStream(filePath);
  147. res.data.pipe(file)
  148. .on('close', () => file.close())
  149. .on('finish', () => {
  150. return resolve();
  151. });
  152. }
  153. else {
  154. rejects(res.status);
  155. }
  156. }).catch((err) => {
  157. logger.error(err);
  158. // eslint-disable-next-line prefer-promise-reject-errors
  159. rejects('Filed to download file.');
  160. });
  161. });
  162. }
  163. private async unzip(zipFilePath: fs.PathLike, unzippedPath: fs.PathLike): Promise<void> {
  164. try {
  165. const stream = fs.createReadStream(zipFilePath);
  166. const unzipStream = stream.pipe(unzipper.Extract({ path: unzippedPath }));
  167. await streamToPromise(unzipStream);
  168. await fs.promises.rm(zipFilePath);
  169. }
  170. catch (err) {
  171. logger.error(err);
  172. throw new Error('Filed to unzip.');
  173. }
  174. }
  175. private async savePluginMetaData(plugins: IGrowiPlugin[]): Promise<void> {
  176. await GrowiPlugin.insertMany(plugins);
  177. }
  178. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, max-len
  179. private static async detectPlugins(origin: IGrowiPluginOrigin, ghOrganizationName: string, ghReposName: string, parentPackageJson?: any): Promise<IGrowiPlugin[]> {
  180. const packageJsonPath = path.resolve(pluginStoringPath, ghReposName, 'package.json');
  181. const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
  182. const { growiPlugin } = packageJson;
  183. const {
  184. name: packageName, description: packageDesc, author: packageAuthor,
  185. } = parentPackageJson ?? packageJson;
  186. if (growiPlugin == null) {
  187. throw new Error('This package does not include \'growiPlugin\' section.');
  188. }
  189. // detect sub plugins for monorepo
  190. if (growiPlugin.isMonorepo && growiPlugin.packages != null) {
  191. const plugins = await Promise.all(
  192. growiPlugin.packages.map(async(subPackagePath) => {
  193. const subPackageInstalledPath = path.join(ghReposName, subPackagePath);
  194. return this.detectPlugins(origin, subPackageInstalledPath, packageJson);
  195. }),
  196. );
  197. return plugins.flat();
  198. }
  199. if (growiPlugin.types == null) {
  200. throw new Error('\'growiPlugin\' section must have a \'types\' property.');
  201. }
  202. const plugin = {
  203. isEnabled: true,
  204. installedPath: `${ghOrganizationName}/${ghReposName}`,
  205. organizationName: ghOrganizationName,
  206. origin,
  207. meta: {
  208. name: growiPlugin.name ?? packageName,
  209. desc: growiPlugin.desc ?? packageDesc,
  210. author: growiPlugin.author ?? packageAuthor,
  211. types: growiPlugin.types,
  212. },
  213. };
  214. // add theme metadata
  215. if (growiPlugin.types.includes(GrowiPluginType.Theme)) {
  216. (plugin as IGrowiPlugin<IGrowiThemePluginMeta>).meta = {
  217. ...plugin.meta,
  218. themes: growiPlugin.themes,
  219. };
  220. }
  221. logger.info('Plugin detected => ', plugin);
  222. return [plugin];
  223. }
  224. async listPlugins(): Promise<IGrowiPlugin[]> {
  225. return [];
  226. }
  227. /**
  228. * Delete plugin
  229. */
  230. async deletePlugin(pluginId: mongoose.Types.ObjectId): Promise<string> {
  231. const deleteFolder = (path: fs.PathLike): Promise<void> => {
  232. return fs.promises.rm(path, { recursive: true });
  233. };
  234. const growiPlugins = await GrowiPlugin.findById(pluginId);
  235. if (growiPlugins == null) {
  236. throw new Error('No plugin found for this ID.');
  237. }
  238. try {
  239. const growiPluginsPath = path.join(pluginStoringPath, growiPlugins.installedPath);
  240. await deleteFolder(growiPluginsPath);
  241. }
  242. catch (err) {
  243. logger.error(err);
  244. throw new Error('Filed to delete plugin repository.');
  245. }
  246. try {
  247. await GrowiPlugin.deleteOne({ _id: pluginId });
  248. }
  249. catch (err) {
  250. logger.error(err);
  251. throw new Error('Filed to delete plugin from GrowiPlugin documents.');
  252. }
  253. return growiPlugins.meta.name;
  254. }
  255. async findThemePlugin(theme: string): Promise<FindThemePluginResult | null> {
  256. let matchedPlugin: IGrowiPlugin | undefined;
  257. let matchedThemeMetadata: GrowiThemeMetadata | undefined;
  258. try {
  259. // retrieve plugin manifests
  260. const growiPlugins = await GrowiPlugin.findEnabledPluginsIncludingAnyTypes([GrowiPluginType.Theme]) as IGrowiPlugin<IGrowiThemePluginMeta>[];
  261. growiPlugins
  262. .forEach(async(growiPlugin) => {
  263. const themeMetadatas = growiPlugin.meta.themes;
  264. const themeMetadata = themeMetadatas.find(t => t.name === theme);
  265. // found
  266. if (themeMetadata != null) {
  267. matchedPlugin = growiPlugin;
  268. matchedThemeMetadata = themeMetadata;
  269. }
  270. });
  271. }
  272. catch (e) {
  273. logger.error(`Could not find the theme '${theme}' from GrowiPlugin documents.`, e);
  274. }
  275. if (matchedPlugin == null || matchedThemeMetadata == null) {
  276. return null;
  277. }
  278. let themeHref;
  279. try {
  280. const manifest = retrievePluginManifest(matchedPlugin);
  281. themeHref = `${PLUGINS_STATIC_DIR}/${matchedPlugin.installedPath}/dist/${manifest[matchedThemeMetadata.manifestKey].file}`;
  282. }
  283. catch (e) {
  284. logger.error(`Could not read manifest file for the theme '${theme}'`, e);
  285. }
  286. return { growiPlugin: matchedPlugin, themeMetadata: matchedThemeMetadata, themeHref };
  287. }
  288. async retrieveAllPluginResourceEntries(): Promise<GrowiPluginResourceEntries> {
  289. const entries: GrowiPluginResourceEntries = [];
  290. try {
  291. const growiPlugins = await GrowiPlugin.findEnabledPlugins();
  292. growiPlugins.forEach(async(growiPlugin) => {
  293. try {
  294. const { types } = growiPlugin.meta;
  295. const manifest = await retrievePluginManifest(growiPlugin);
  296. // add script
  297. if (types.includes(GrowiPluginType.Script)) {
  298. const href = `${PLUGINS_STATIC_DIR}/${growiPlugin.installedPath}/dist/${manifest['client-entry.tsx'].file}`;
  299. entries.push([growiPlugin.installedPath, href]);
  300. }
  301. // add link
  302. if (types.includes(GrowiPluginType.Script) || types.includes(GrowiPluginType.Style)) {
  303. const href = `${PLUGINS_STATIC_DIR}/${growiPlugin.installedPath}/dist/${manifest['client-entry.tsx'].css}`;
  304. entries.push([growiPlugin.installedPath, href]);
  305. }
  306. }
  307. catch (e) {
  308. logger.warn(e);
  309. }
  310. });
  311. }
  312. catch (e) {
  313. logger.error('Could not retrieve GrowiPlugin documents.', e);
  314. }
  315. return entries;
  316. }
  317. }
  318. export const growiPluginService = new GrowiPluginService();