growi-plugin.ts 13 KB

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