index.js 20 KB

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