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 AttachmentService from '../service/attachment';
  17. import { SlackIntegrationService } from '../service/slack-integration';
  18. import { UserNotificationService } from '../service/user-notification';
  19. const logger = loggerFactory('growi:crowi');
  20. const httpErrorHandler = require('../middlewares/http-error-handler');
  21. const models = require('../models');
  22. const PluginService = require('../plugins/plugin.service');
  23. const sep = path.sep;
  24. function Crowi() {
  25. this.version = pkg.version;
  26. this.runtimeVersions = undefined; // initialized by scanRuntimeVersions()
  27. this.publicDir = path.join(projectRoot, 'public') + sep;
  28. this.resourceDir = path.join(projectRoot, 'resource') + sep;
  29. this.localeDir = path.join(this.resourceDir, 'locales') + sep;
  30. this.viewsDir = path.resolve(__dirname, '../views') + sep;
  31. this.tmpDir = path.join(projectRoot, 'tmp') + sep;
  32. this.cacheDir = path.join(this.tmpDir, 'cache');
  33. this.express = null;
  34. this.config = {};
  35. this.configManager = null;
  36. this.s2sMessagingService = null;
  37. this.mailService = null;
  38. this.passportService = null;
  39. this.globalNotificationService = null;
  40. this.userNotificationService = null;
  41. this.xssService = null;
  42. this.aclService = null;
  43. this.appService = null;
  44. this.fileUploadService = null;
  45. this.restQiitaAPIService = null;
  46. this.growiBridgeService = null;
  47. this.exportService = null;
  48. this.importService = null;
  49. this.searchService = null;
  50. this.socketIoService = null;
  51. this.pageService = null;
  52. this.syncPageStatusService = null;
  53. this.cdnResourcesService = new CdnResourcesService();
  54. this.interceptorManager = new InterceptorManager();
  55. this.slackIntegrationService = null;
  56. this.xss = new Xss();
  57. this.tokens = null;
  58. this.models = {};
  59. this.env = process.env;
  60. this.node_env = this.env.NODE_ENV || 'development';
  61. this.port = this.env.PORT || 3000;
  62. this.events = {
  63. user: new (require('../events/user'))(this),
  64. page: new (require('../events/page'))(this),
  65. bookmark: new (require('../events/bookmark'))(this),
  66. comment: new (require('../events/comment'))(this),
  67. tag: new (require('../events/tag'))(this),
  68. admin: new (require('../events/admin'))(this),
  69. };
  70. }
  71. Crowi.prototype.init = async function() {
  72. await this.setupDatabase();
  73. await this.setupModels();
  74. await this.setupConfigManager();
  75. await this.setupSessionConfig();
  76. // setup messaging services
  77. await this.setupS2sMessagingService();
  78. await this.setupSocketIoService();
  79. // customizeService depends on AppService and XssService
  80. // passportService depends on appService
  81. // export and import depends on setUpGrowiBridge
  82. await Promise.all([
  83. this.setUpApp(),
  84. this.setUpXss(),
  85. this.setUpGrowiBridge(),
  86. ]);
  87. await Promise.all([
  88. this.scanRuntimeVersions(),
  89. this.setupPassport(),
  90. this.setupSearcher(),
  91. this.setupMailer(),
  92. this.setupSlackIntegrationService(),
  93. this.setupCsrf(),
  94. this.setUpFileUpload(),
  95. this.setUpFileUploaderSwitchService(),
  96. this.setupAttachmentService(),
  97. this.setUpAcl(),
  98. this.setUpCustomize(),
  99. this.setUpRestQiitaAPI(),
  100. this.setupUserGroup(),
  101. this.setupExport(),
  102. this.setupImport(),
  103. this.setupPageService(),
  104. this.setupSyncPageStatusService(),
  105. ]);
  106. // globalNotification depends on slack and mailer
  107. await Promise.all([
  108. this.setUpGlobalNotification(),
  109. this.setUpUserNotification(),
  110. ]);
  111. };
  112. Crowi.prototype.initForTest = async function() {
  113. await this.setupModels();
  114. await this.setupConfigManager();
  115. // // customizeService depends on AppService and XssService
  116. // // passportService depends on appService
  117. await Promise.all([
  118. this.setUpApp(),
  119. this.setUpXss(),
  120. // this.setUpGrowiBridge(),
  121. ]);
  122. await Promise.all([
  123. // this.scanRuntimeVersions(),
  124. this.setupPassport(),
  125. // this.setupSearcher(),
  126. // this.setupMailer(),
  127. // this.setupSlackIntegrationService(),
  128. // this.setupCsrf(),
  129. // this.setUpFileUpload(),
  130. this.setupAttachmentService(),
  131. this.setUpAcl(),
  132. // this.setUpCustomize(),
  133. // this.setUpRestQiitaAPI(),
  134. // this.setupUserGroup(),
  135. // this.setupExport(),
  136. // this.setupImport(),
  137. this.setupPageService(),
  138. ]);
  139. // globalNotification depends on slack and mailer
  140. // await Promise.all([
  141. // this.setUpGlobalNotification(),
  142. // ]);
  143. };
  144. Crowi.prototype.isPageId = function(pageId) {
  145. if (!pageId) {
  146. return false;
  147. }
  148. if (typeof pageId === 'string' && pageId.match(/^[\da-f]{24}$/)) {
  149. return true;
  150. }
  151. return false;
  152. };
  153. Crowi.prototype.setConfig = function(config) {
  154. this.config = config;
  155. };
  156. Crowi.prototype.getConfig = function() {
  157. return this.config;
  158. };
  159. Crowi.prototype.getEnv = function() {
  160. return this.env;
  161. };
  162. // getter/setter of model instance
  163. //
  164. Crowi.prototype.model = function(name, model) {
  165. if (model != null) {
  166. this.models[name] = model;
  167. }
  168. return this.models[name];
  169. };
  170. // getter/setter of event instance
  171. Crowi.prototype.event = function(name, event) {
  172. if (event) {
  173. this.events[name] = event;
  174. }
  175. return this.events[name];
  176. };
  177. Crowi.prototype.setupDatabase = function() {
  178. mongoose.Promise = global.Promise;
  179. // mongoUri = mongodb://user:password@host/dbname
  180. const mongoUri = getMongoUri();
  181. initMongooseGlobalSettings();
  182. return mongoose.connect(mongoUri, mongoOptions);
  183. };
  184. Crowi.prototype.setupSessionConfig = async function() {
  185. const session = require('express-session');
  186. const sessionMaxAge = this.configManager.getConfig('crowi', 'security:sessionMaxAge') || 2592000000; // default: 30days
  187. const redisUrl = this.env.REDISTOGO_URL || this.env.REDIS_URI || this.env.REDIS_URL || null;
  188. const uid = require('uid-safe').sync;
  189. // generate pre-defined uid for healthcheck
  190. const healthcheckUid = uid(24);
  191. const sessionConfig = {
  192. rolling: true,
  193. secret: this.env.SECRET_TOKEN || 'this is default session secret',
  194. resave: false,
  195. saveUninitialized: true,
  196. cookie: {
  197. maxAge: sessionMaxAge,
  198. },
  199. genid(req) {
  200. // return pre-defined uid when healthcheck
  201. if (req.path === '/_api/v3/healthcheck') {
  202. return healthcheckUid;
  203. }
  204. return uid(24);
  205. },
  206. };
  207. if (this.env.SESSION_NAME) {
  208. sessionConfig.name = this.env.SESSION_NAME;
  209. }
  210. // use Redis for session store
  211. if (redisUrl) {
  212. const redis = require('redis');
  213. const redisClient = redis.createClient({ url: redisUrl });
  214. const RedisStore = require('connect-redis')(session);
  215. sessionConfig.store = new RedisStore({ client: redisClient });
  216. }
  217. // use MongoDB for session store
  218. else {
  219. const MongoStore = require('connect-mongo');
  220. sessionConfig.store = MongoStore.create({ client: mongoose.connection.getClient() });
  221. }
  222. this.sessionConfig = sessionConfig;
  223. };
  224. Crowi.prototype.setupConfigManager = async function() {
  225. this.configManager = new ConfigManager();
  226. return this.configManager.loadConfigs();
  227. };
  228. Crowi.prototype.setupS2sMessagingService = async function() {
  229. const s2sMessagingService = require('../service/s2s-messaging')(this);
  230. if (s2sMessagingService != null) {
  231. s2sMessagingService.subscribe();
  232. this.configManager.setS2sMessagingService(s2sMessagingService);
  233. // add as a message handler
  234. s2sMessagingService.addMessageHandler(this.configManager);
  235. this.s2sMessagingService = s2sMessagingService;
  236. }
  237. };
  238. Crowi.prototype.setupSocketIoService = async function() {
  239. const SocketIoService = require('../service/socket-io');
  240. if (this.socketIoService == null) {
  241. this.socketIoService = new SocketIoService(this);
  242. }
  243. };
  244. Crowi.prototype.setupModels = async function() {
  245. Object.keys(models).forEach((key) => {
  246. return this.model(key, models[key](this));
  247. });
  248. };
  249. Crowi.prototype.scanRuntimeVersions = async function() {
  250. const self = this;
  251. const check = require('check-node-version');
  252. return new Promise((resolve, reject) => {
  253. check((err, result) => {
  254. if (err) {
  255. reject(err);
  256. }
  257. self.runtimeVersions = result;
  258. resolve();
  259. });
  260. });
  261. };
  262. Crowi.prototype.getSlack = function() {
  263. return this.slack;
  264. };
  265. Crowi.prototype.getSlackLegacy = function() {
  266. return this.slackLegacy;
  267. };
  268. Crowi.prototype.getInterceptorManager = function() {
  269. return this.interceptorManager;
  270. };
  271. Crowi.prototype.getGlobalNotificationService = function() {
  272. return this.globalNotificationService;
  273. };
  274. Crowi.prototype.getUserNotificationService = function() {
  275. return this.userNotificationService;
  276. };
  277. Crowi.prototype.getRestQiitaAPIService = function() {
  278. return this.restQiitaAPIService;
  279. };
  280. Crowi.prototype.setupPassport = async function() {
  281. logger.debug('Passport is enabled');
  282. // initialize service
  283. const PassportService = require('../service/passport');
  284. if (this.passportService == null) {
  285. this.passportService = new PassportService(this);
  286. }
  287. this.passportService.setupSerializer();
  288. // setup strategies
  289. try {
  290. this.passportService.setupStrategyById('local');
  291. this.passportService.setupStrategyById('ldap');
  292. this.passportService.setupStrategyById('saml');
  293. this.passportService.setupStrategyById('oidc');
  294. this.passportService.setupStrategyById('basic');
  295. this.passportService.setupStrategyById('google');
  296. this.passportService.setupStrategyById('github');
  297. this.passportService.setupStrategyById('twitter');
  298. }
  299. catch (err) {
  300. logger.error(err);
  301. }
  302. // add as a message handler
  303. if (this.s2sMessagingService != null) {
  304. this.s2sMessagingService.addMessageHandler(this.passportService);
  305. }
  306. return Promise.resolve();
  307. };
  308. Crowi.prototype.setupSearcher = async function() {
  309. const SearchService = require('~/server/service/search');
  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;