index.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. /* eslint-disable @typescript-eslint/no-this-alias */
  2. import path from 'path';
  3. import http from 'http';
  4. import mongoose from 'mongoose';
  5. import { createTerminus } from '@godaddy/terminus';
  6. import { initMongooseGlobalSettings, getMongoUri, mongoOptions } from '@growi/core';
  7. import pkg from '^/package.json';
  8. import CdnResourcesService from '~/services/cdn-resources-service';
  9. import InterceptorManager from '~/services/interceptor-manager';
  10. import Xss from '~/services/xss';
  11. import loggerFactory from '~/utils/logger';
  12. import { projectRoot } from '~/utils/project-dir-utils';
  13. import ConfigManager from '../service/config-manager';
  14. import AppService from '../service/app';
  15. import AclService from '../service/acl';
  16. import SearchService from '../service/search';
  17. import AttachmentService from '../service/attachment';
  18. import { SlackIntegrationService } from '../service/slack-integration';
  19. import { UserNotificationService } from '../service/user-notification';
  20. const logger = loggerFactory('growi:crowi');
  21. const httpErrorHandler = require('../middlewares/http-error-handler');
  22. const models = require('../models');
  23. const PluginService = require('../plugins/plugin.service');
  24. const sep = path.sep;
  25. function Crowi() {
  26. this.version = pkg.version;
  27. this.runtimeVersions = undefined; // initialized by scanRuntimeVersions()
  28. this.publicDir = path.join(projectRoot, 'public') + sep;
  29. this.resourceDir = path.join(projectRoot, 'resource') + sep;
  30. this.localeDir = path.join(this.resourceDir, 'locales') + sep;
  31. this.viewsDir = path.resolve(__dirname, '../views') + sep;
  32. this.tmpDir = path.join(projectRoot, 'tmp') + sep;
  33. this.cacheDir = path.join(this.tmpDir, 'cache');
  34. this.express = null;
  35. this.config = {};
  36. this.configManager = null;
  37. this.s2sMessagingService = null;
  38. this.mailService = null;
  39. this.passportService = null;
  40. this.globalNotificationService = null;
  41. this.userNotificationService = null;
  42. this.xssService = null;
  43. this.aclService = null;
  44. this.appService = null;
  45. this.fileUploadService = null;
  46. this.restQiitaAPIService = null;
  47. this.growiBridgeService = null;
  48. this.exportService = null;
  49. this.importService = null;
  50. this.searchService = null;
  51. this.socketIoService = null;
  52. this.pageService = null;
  53. this.syncPageStatusService = null;
  54. this.cdnResourcesService = new CdnResourcesService();
  55. this.interceptorManager = new InterceptorManager();
  56. this.slackIntegrationService = null;
  57. this.xss = new Xss();
  58. this.tokens = null;
  59. this.models = {};
  60. this.env = process.env;
  61. this.node_env = this.env.NODE_ENV || 'development';
  62. this.port = this.env.PORT || 3000;
  63. this.events = {
  64. user: new (require('../events/user'))(this),
  65. page: new (require('../events/page'))(this),
  66. bookmark: new (require('../events/bookmark'))(this),
  67. comment: new (require('../events/comment'))(this),
  68. tag: new (require('../events/tag'))(this),
  69. admin: new (require('../events/admin'))(this),
  70. };
  71. }
  72. Crowi.prototype.init = async function() {
  73. await this.setupDatabase();
  74. await this.setupModels();
  75. await this.setupConfigManager();
  76. await this.setupSessionConfig();
  77. // setup messaging services
  78. await this.setupS2sMessagingService();
  79. await this.setupSocketIoService();
  80. // customizeService depends on AppService and XssService
  81. // passportService depends on appService
  82. // export and import depends on setUpGrowiBridge
  83. await Promise.all([
  84. this.setUpApp(),
  85. this.setUpXss(),
  86. this.setUpGrowiBridge(),
  87. ]);
  88. await Promise.all([
  89. this.scanRuntimeVersions(),
  90. this.setupPassport(),
  91. this.setupSearcher(),
  92. this.setupMailer(),
  93. this.setupSlackIntegrationService(),
  94. this.setupCsrf(),
  95. this.setUpFileUpload(),
  96. this.setUpFileUploaderSwitchService(),
  97. this.setupAttachmentService(),
  98. this.setUpAcl(),
  99. this.setUpCustomize(),
  100. this.setUpRestQiitaAPI(),
  101. this.setupUserGroup(),
  102. this.setupExport(),
  103. this.setupImport(),
  104. this.setupPageService(),
  105. this.setupSyncPageStatusService(),
  106. ]);
  107. // globalNotification depends on slack and mailer
  108. await Promise.all([
  109. this.setUpGlobalNotification(),
  110. this.setUpUserNotification(),
  111. ]);
  112. };
  113. Crowi.prototype.initForTest = async function() {
  114. await this.setupModels();
  115. await this.setupConfigManager();
  116. // // customizeService depends on AppService and XssService
  117. // // passportService depends on appService
  118. await Promise.all([
  119. this.setUpApp(),
  120. this.setUpXss(),
  121. // this.setUpGrowiBridge(),
  122. ]);
  123. await Promise.all([
  124. // this.scanRuntimeVersions(),
  125. this.setupPassport(),
  126. // this.setupSearcher(),
  127. // this.setupMailer(),
  128. // this.setupSlackIntegrationService(),
  129. // this.setupCsrf(),
  130. // this.setUpFileUpload(),
  131. this.setupAttachmentService(),
  132. this.setUpAcl(),
  133. // this.setUpCustomize(),
  134. // this.setUpRestQiitaAPI(),
  135. // this.setupUserGroup(),
  136. // this.setupExport(),
  137. // this.setupImport(),
  138. this.setupPageService(),
  139. ]);
  140. // globalNotification depends on slack and mailer
  141. // await Promise.all([
  142. // this.setUpGlobalNotification(),
  143. // ]);
  144. };
  145. Crowi.prototype.isPageId = function(pageId) {
  146. if (!pageId) {
  147. return false;
  148. }
  149. if (typeof pageId === 'string' && pageId.match(/^[\da-f]{24}$/)) {
  150. return true;
  151. }
  152. return false;
  153. };
  154. Crowi.prototype.setConfig = function(config) {
  155. this.config = config;
  156. };
  157. Crowi.prototype.getConfig = function() {
  158. return this.config;
  159. };
  160. Crowi.prototype.getEnv = function() {
  161. return this.env;
  162. };
  163. // getter/setter of model instance
  164. //
  165. Crowi.prototype.model = function(name, model) {
  166. if (model != null) {
  167. this.models[name] = model;
  168. }
  169. return this.models[name];
  170. };
  171. // getter/setter of event instance
  172. Crowi.prototype.event = function(name, event) {
  173. if (event) {
  174. this.events[name] = event;
  175. }
  176. return this.events[name];
  177. };
  178. Crowi.prototype.setupDatabase = function() {
  179. mongoose.Promise = global.Promise;
  180. // mongoUri = mongodb://user:password@host/dbname
  181. const mongoUri = getMongoUri();
  182. initMongooseGlobalSettings();
  183. return mongoose.connect(mongoUri, mongoOptions);
  184. };
  185. Crowi.prototype.setupSessionConfig = async function() {
  186. const session = require('express-session');
  187. const sessionMaxAge = this.configManager.getConfig('crowi', 'security:sessionMaxAge') || 2592000000; // default: 30days
  188. const redisUrl = this.env.REDISTOGO_URL || this.env.REDIS_URI || this.env.REDIS_URL || null;
  189. const uid = require('uid-safe').sync;
  190. // generate pre-defined uid for healthcheck
  191. const healthcheckUid = uid(24);
  192. const sessionConfig = {
  193. rolling: true,
  194. secret: this.env.SECRET_TOKEN || 'this is default session secret',
  195. resave: false,
  196. saveUninitialized: true,
  197. cookie: {
  198. maxAge: sessionMaxAge,
  199. },
  200. genid(req) {
  201. // return pre-defined uid when healthcheck
  202. if (req.path === '/_api/v3/healthcheck') {
  203. return healthcheckUid;
  204. }
  205. return uid(24);
  206. },
  207. };
  208. if (this.env.SESSION_NAME) {
  209. sessionConfig.name = this.env.SESSION_NAME;
  210. }
  211. // use Redis for session store
  212. if (redisUrl) {
  213. const redis = require('redis');
  214. const redisClient = redis.createClient({ url: redisUrl });
  215. const RedisStore = require('connect-redis')(session);
  216. sessionConfig.store = new RedisStore({ client: redisClient });
  217. }
  218. // use MongoDB for session store
  219. else {
  220. const MongoStore = require('connect-mongo');
  221. sessionConfig.store = MongoStore.create({ client: mongoose.connection.getClient() });
  222. }
  223. this.sessionConfig = sessionConfig;
  224. };
  225. Crowi.prototype.setupConfigManager = async function() {
  226. this.configManager = new ConfigManager();
  227. return this.configManager.loadConfigs();
  228. };
  229. Crowi.prototype.setupS2sMessagingService = async function() {
  230. const s2sMessagingService = require('../service/s2s-messaging')(this);
  231. if (s2sMessagingService != null) {
  232. s2sMessagingService.subscribe();
  233. this.configManager.setS2sMessagingService(s2sMessagingService);
  234. // add as a message handler
  235. s2sMessagingService.addMessageHandler(this.configManager);
  236. this.s2sMessagingService = s2sMessagingService;
  237. }
  238. };
  239. Crowi.prototype.setupSocketIoService = async function() {
  240. const SocketIoService = require('../service/socket-io');
  241. if (this.socketIoService == null) {
  242. this.socketIoService = new SocketIoService(this);
  243. }
  244. };
  245. Crowi.prototype.setupModels = async function() {
  246. Object.keys(models).forEach((key) => {
  247. return this.model(key, models[key](this));
  248. });
  249. };
  250. Crowi.prototype.scanRuntimeVersions = async function() {
  251. const self = this;
  252. const check = require('check-node-version');
  253. return new Promise((resolve, reject) => {
  254. check((err, result) => {
  255. if (err) {
  256. reject(err);
  257. }
  258. self.runtimeVersions = result;
  259. resolve();
  260. });
  261. });
  262. };
  263. Crowi.prototype.getSlack = function() {
  264. return this.slack;
  265. };
  266. Crowi.prototype.getSlackLegacy = function() {
  267. return this.slackLegacy;
  268. };
  269. Crowi.prototype.getInterceptorManager = function() {
  270. return this.interceptorManager;
  271. };
  272. Crowi.prototype.getGlobalNotificationService = function() {
  273. return this.globalNotificationService;
  274. };
  275. Crowi.prototype.getUserNotificationService = function() {
  276. return this.userNotificationService;
  277. };
  278. Crowi.prototype.getRestQiitaAPIService = function() {
  279. return this.restQiitaAPIService;
  280. };
  281. Crowi.prototype.setupPassport = async function() {
  282. logger.debug('Passport is enabled');
  283. // initialize service
  284. const PassportService = require('../service/passport');
  285. if (this.passportService == null) {
  286. this.passportService = new PassportService(this);
  287. }
  288. this.passportService.setupSerializer();
  289. // setup strategies
  290. try {
  291. this.passportService.setupStrategyById('local');
  292. this.passportService.setupStrategyById('ldap');
  293. this.passportService.setupStrategyById('saml');
  294. this.passportService.setupStrategyById('oidc');
  295. this.passportService.setupStrategyById('basic');
  296. this.passportService.setupStrategyById('google');
  297. this.passportService.setupStrategyById('github');
  298. this.passportService.setupStrategyById('twitter');
  299. }
  300. catch (err) {
  301. logger.error(err);
  302. }
  303. // add as a message handler
  304. if (this.s2sMessagingService != null) {
  305. this.s2sMessagingService.addMessageHandler(this.passportService);
  306. }
  307. return Promise.resolve();
  308. };
  309. Crowi.prototype.setupSearcher = async function() {
  310. this.searchService = new SearchService(this);
  311. };
  312. Crowi.prototype.setupMailer = async function() {
  313. const MailService = require('~/server/service/mail');
  314. this.mailService = new MailService(this);
  315. // add as a message handler
  316. if (this.s2sMessagingService != null) {
  317. this.s2sMessagingService.addMessageHandler(this.mailService);
  318. }
  319. };
  320. Crowi.prototype.setupCsrf = async function() {
  321. const Tokens = require('csrf');
  322. this.tokens = new Tokens();
  323. return Promise.resolve();
  324. };
  325. Crowi.prototype.getTokens = function() {
  326. return this.tokens;
  327. };
  328. Crowi.prototype.start = async function() {
  329. // init CrowiDev
  330. if (this.node_env === 'development') {
  331. const CrowiDev = require('./dev');
  332. this.crowiDev = new CrowiDev(this);
  333. this.crowiDev.init();
  334. }
  335. await this.init();
  336. await this.buildServer();
  337. const { express, configManager } = this;
  338. // setup plugins
  339. this.pluginService = new PluginService(this, express);
  340. await this.pluginService.autoDetectAndLoadPlugins();
  341. const app = (this.node_env === 'development') ? this.crowiDev.setupServer(express) : express;
  342. const httpServer = http.createServer(app);
  343. // setup terminus
  344. this.setupTerminus(httpServer);
  345. // attach to socket.io
  346. this.socketIoService.attachServer(httpServer);
  347. // listen
  348. const serverListening = httpServer.listen(this.port, () => {
  349. logger.info(`[${this.node_env}] Express server is listening on port ${this.port}`);
  350. if (this.node_env === 'development') {
  351. this.crowiDev.setupExpressAfterListening(express);
  352. }
  353. });
  354. // listen for promster
  355. if (configManager.getConfig('crowi', 'promster:isEnabled')) {
  356. const { createServer } = require('@promster/server');
  357. const promsterPort = configManager.getConfig('crowi', 'promster:port');
  358. createServer({ port: promsterPort }).then(() => {
  359. logger.info(`[${this.node_env}] Promster server is listening on port ${promsterPort}`);
  360. });
  361. }
  362. // setup Express Routes
  363. this.setupRoutesAtLast();
  364. // setup Global Error Handlers
  365. this.setupGlobalErrorHandlers();
  366. return serverListening;
  367. };
  368. Crowi.prototype.buildServer = async function() {
  369. const env = this.node_env;
  370. const express = require('express')();
  371. require('./express-init')(this, express);
  372. // use bunyan
  373. if (env === 'production') {
  374. const expressBunyanLogger = require('express-bunyan-logger');
  375. const logger = loggerFactory('express');
  376. express.use(expressBunyanLogger({
  377. logger,
  378. excludes: ['*'],
  379. }));
  380. }
  381. // use morgan
  382. else {
  383. const morgan = require('morgan');
  384. express.use(morgan('dev'));
  385. }
  386. this.express = express;
  387. };
  388. Crowi.prototype.setupTerminus = function(server) {
  389. createTerminus(server, {
  390. signals: ['SIGINT', 'SIGTERM'],
  391. onSignal: async() => {
  392. logger.info('Server is starting cleanup');
  393. await mongoose.disconnect();
  394. return;
  395. },
  396. onShutdown: async() => {
  397. logger.info('Cleanup finished, server is shutting down');
  398. },
  399. });
  400. };
  401. /**
  402. * setup Express Routes
  403. * !! this must be at last because it includes '/*' route !!
  404. */
  405. Crowi.prototype.setupRoutesAtLast = function() {
  406. require('../routes')(this, this.express);
  407. };
  408. /**
  409. * setup global error handlers
  410. * !! this must be after the Routes setup !!
  411. */
  412. Crowi.prototype.setupGlobalErrorHandlers = function() {
  413. this.express.use(httpErrorHandler);
  414. };
  415. /**
  416. * require API for plugins
  417. *
  418. * @param {string} modulePath relative path from /lib/crowi/index.js
  419. * @return {module}
  420. *
  421. * @memberof Crowi
  422. */
  423. Crowi.prototype.require = function(modulePath) {
  424. return require(modulePath);
  425. };
  426. /**
  427. * setup GlobalNotificationService
  428. */
  429. Crowi.prototype.setUpGlobalNotification = async function() {
  430. const GlobalNotificationService = require('../service/global-notification');
  431. if (this.globalNotificationService == null) {
  432. this.globalNotificationService = new GlobalNotificationService(this);
  433. }
  434. };
  435. /**
  436. * setup UserNotificationService
  437. */
  438. Crowi.prototype.setUpUserNotification = async function() {
  439. if (this.userNotificationService == null) {
  440. this.userNotificationService = new UserNotificationService(this);
  441. }
  442. };
  443. /**
  444. * setup XssService
  445. */
  446. Crowi.prototype.setUpXss = async function() {
  447. const XssService = require('../service/xss');
  448. if (this.xssService == null) {
  449. this.xssService = new XssService(this.configManager);
  450. }
  451. };
  452. /**
  453. * setup AclService
  454. */
  455. Crowi.prototype.setUpAcl = async function() {
  456. if (this.aclService == null) {
  457. this.aclService = new AclService(this.configManager);
  458. }
  459. };
  460. /**
  461. * setup CustomizeService
  462. */
  463. Crowi.prototype.setUpCustomize = async function() {
  464. const CustomizeService = require('../service/customize');
  465. if (this.customizeService == null) {
  466. this.customizeService = new CustomizeService(this);
  467. this.customizeService.initCustomCss();
  468. this.customizeService.initCustomTitle();
  469. // add as a message handler
  470. if (this.s2sMessagingService != null) {
  471. this.s2sMessagingService.addMessageHandler(this.customizeService);
  472. }
  473. }
  474. };
  475. /**
  476. * setup AppService
  477. */
  478. Crowi.prototype.setUpApp = async function() {
  479. if (this.appService == null) {
  480. this.appService = new AppService(this);
  481. // add as a message handler
  482. const isInstalled = this.configManager.getConfig('crowi', 'app:installed');
  483. if (this.s2sMessagingService != null && !isInstalled) {
  484. this.s2sMessagingService.addMessageHandler(this.appService);
  485. }
  486. }
  487. };
  488. /**
  489. * setup FileUploadService
  490. */
  491. Crowi.prototype.setUpFileUpload = async function(isForceUpdate = false) {
  492. if (this.fileUploadService == null || isForceUpdate) {
  493. this.fileUploadService = require('../service/file-uploader')(this);
  494. }
  495. };
  496. /**
  497. * setup FileUploaderSwitchService
  498. */
  499. Crowi.prototype.setUpFileUploaderSwitchService = async function() {
  500. const FileUploaderSwitchService = require('../service/file-uploader-switch');
  501. this.fileUploaderSwitchService = new FileUploaderSwitchService(this);
  502. // add as a message handler
  503. if (this.s2sMessagingService != null) {
  504. this.s2sMessagingService.addMessageHandler(this.fileUploaderSwitchService);
  505. }
  506. };
  507. /**
  508. * setup AttachmentService
  509. */
  510. Crowi.prototype.setupAttachmentService = async function() {
  511. if (this.attachmentService == null) {
  512. this.attachmentService = new AttachmentService(this);
  513. }
  514. };
  515. /**
  516. * setup RestQiitaAPIService
  517. */
  518. Crowi.prototype.setUpRestQiitaAPI = async function() {
  519. const RestQiitaAPIService = require('../service/rest-qiita-API');
  520. if (this.restQiitaAPIService == null) {
  521. this.restQiitaAPIService = new RestQiitaAPIService(this);
  522. }
  523. };
  524. Crowi.prototype.setupUserGroup = async function() {
  525. const UserGroupService = require('../service/user-group');
  526. if (this.userGroupService == null) {
  527. this.userGroupService = new UserGroupService(this);
  528. return this.userGroupService.init();
  529. }
  530. };
  531. Crowi.prototype.setUpGrowiBridge = async function() {
  532. const GrowiBridgeService = require('../service/growi-bridge');
  533. if (this.growiBridgeService == null) {
  534. this.growiBridgeService = new GrowiBridgeService(this);
  535. }
  536. };
  537. Crowi.prototype.setupExport = async function() {
  538. const ExportService = require('../service/export');
  539. if (this.exportService == null) {
  540. this.exportService = new ExportService(this);
  541. }
  542. };
  543. Crowi.prototype.setupImport = async function() {
  544. const ImportService = require('../service/import');
  545. if (this.importService == null) {
  546. this.importService = new ImportService(this);
  547. }
  548. };
  549. Crowi.prototype.setupPageService = async function() {
  550. const PageEventService = require('../service/page');
  551. if (this.pageService == null) {
  552. this.pageService = new PageEventService(this);
  553. }
  554. };
  555. Crowi.prototype.setupSyncPageStatusService = async function() {
  556. const SyncPageStatusService = require('../service/system-events/sync-page-status');
  557. if (this.syncPageStatusService == null) {
  558. this.syncPageStatusService = new SyncPageStatusService(this, this.s2sMessagingService, this.socketIoService);
  559. // add as a message handler
  560. if (this.s2sMessagingService != null) {
  561. this.s2sMessagingService.addMessageHandler(this.syncPageStatusService);
  562. }
  563. }
  564. };
  565. Crowi.prototype.setupSlackIntegrationService = async function() {
  566. if (this.slackIntegrationService == null) {
  567. this.slackIntegrationService = new SlackIntegrationService(this);
  568. }
  569. // add as a message handler
  570. if (this.s2sMessagingService != null) {
  571. this.s2sMessagingService.addMessageHandler(this.slackIntegrationService);
  572. }
  573. };
  574. export default Crowi;