index.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. /* eslint-disable @typescript-eslint/no-this-alias */
  2. import path from 'path';
  3. import mongoose from 'mongoose';
  4. import pkg from '^/package.json';
  5. import CdnResourcesService from '~/services/cdn-resources-service';
  6. import InterceptorManager from '~/services/interceptor-manager';
  7. import Xss from '~/services/xss';
  8. import loggerFactory from '~/utils/logger';
  9. import { getMongoUri, mongoOptions } from '~/server/util/mongoose-utils';
  10. import { projectRoot } from '~/utils/project-dir-utils';
  11. import ConfigManager from '../service/config-manager';
  12. import AclService from '../service/acl';
  13. import AttachmentService from '../service/attachment';
  14. const logger = loggerFactory('growi:crowi');
  15. const httpErrorHandler = require('../middlewares/http-error-handler');
  16. const models = require('../models');
  17. const PluginService = require('../plugins/plugin.service');
  18. const sep = path.sep;
  19. function Crowi() {
  20. this.version = pkg.version;
  21. this.runtimeVersions = undefined; // initialized by scanRuntimeVersions()
  22. this.publicDir = path.join(projectRoot, 'public') + sep;
  23. this.resourceDir = path.join(projectRoot, 'resource') + sep;
  24. this.localeDir = path.join(this.resourceDir, 'locales') + sep;
  25. this.viewsDir = path.join(projectRoot, 'src', 'server', 'views') + sep;
  26. this.tmpDir = path.join(projectRoot, 'tmp') + sep;
  27. this.cacheDir = path.join(this.tmpDir, 'cache');
  28. this.express = null;
  29. this.config = {};
  30. this.configManager = null;
  31. this.s2sMessagingService = null;
  32. this.mailService = null;
  33. this.passportService = null;
  34. this.globalNotificationService = null;
  35. this.userNotificationService = null;
  36. this.slackNotificationService = null;
  37. this.xssService = null;
  38. this.aclService = null;
  39. this.appService = null;
  40. this.fileUploadService = null;
  41. this.restQiitaAPIService = null;
  42. this.growiBridgeService = null;
  43. this.exportService = null;
  44. this.importService = null;
  45. this.searchService = null;
  46. this.socketIoService = null;
  47. this.pageService = null;
  48. this.syncPageStatusService = null;
  49. this.cdnResourcesService = new CdnResourcesService();
  50. this.interceptorManager = new InterceptorManager();
  51. this.slackBotService = null;
  52. this.xss = new Xss();
  53. this.tokens = null;
  54. this.models = {};
  55. this.env = process.env;
  56. this.node_env = this.env.NODE_ENV || 'development';
  57. this.port = this.env.PORT || 3000;
  58. this.events = {
  59. user: new (require('../events/user'))(this),
  60. page: new (require('../events/page'))(this),
  61. bookmark: new (require('../events/bookmark'))(this),
  62. tag: new (require('../events/tag'))(this),
  63. admin: new (require('../events/admin'))(this),
  64. };
  65. }
  66. Crowi.prototype.init = async function() {
  67. await this.setupDatabase();
  68. await this.setupModels();
  69. await this.setupConfigManager();
  70. await this.setupSessionConfig();
  71. // setup messaging services
  72. await this.setupS2sMessagingService();
  73. await this.setupSocketIoService();
  74. // customizeService depends on AppService and XssService
  75. // passportService depends on appService
  76. // slack depends on setUpSlacklNotification
  77. // export and import depends on setUpGrowiBridge
  78. await Promise.all([
  79. this.setUpApp(),
  80. this.setUpXss(),
  81. this.setUpSlacklNotification(),
  82. this.setUpGrowiBridge(),
  83. ]);
  84. await Promise.all([
  85. this.scanRuntimeVersions(),
  86. this.setupPassport(),
  87. this.setupSearcher(),
  88. this.setupMailer(),
  89. this.setupSlack(),
  90. this.setupSlackLegacy(),
  91. this.setupCsrf(),
  92. this.setUpFileUpload(),
  93. this.setUpFileUploaderSwitchService(),
  94. this.setupAttachmentService(),
  95. this.setUpAcl(),
  96. this.setUpCustomize(),
  97. this.setUpRestQiitaAPI(),
  98. this.setupUserGroup(),
  99. this.setupExport(),
  100. this.setupImport(),
  101. this.setupPageService(),
  102. this.setupSyncPageStatusService(),
  103. this.setupSlackBotService(),
  104. ]);
  105. // globalNotification depends on slack and mailer
  106. await Promise.all([
  107. this.setUpGlobalNotification(),
  108. this.setUpUserNotification(),
  109. ]);
  110. };
  111. Crowi.prototype.initForTest = async function() {
  112. await this.setupModels();
  113. await this.setupConfigManager();
  114. // // customizeService depends on AppService and XssService
  115. // // passportService depends on appService
  116. // // slack depends on setUpSlacklNotification
  117. await Promise.all([
  118. this.setUpApp(),
  119. this.setUpXss(),
  120. // this.setUpSlacklNotification(),
  121. // this.setUpGrowiBridge(),
  122. ]);
  123. await Promise.all([
  124. // this.scanRuntimeVersions(),
  125. this.setupPassport(),
  126. // this.setupSearcher(),
  127. // this.setupMailer(),
  128. // this.setupSlack(),
  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. 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.setupSlack = async function() {
  321. const self = this;
  322. return new Promise(((resolve, reject) => {
  323. self.slack = require('../util/slack')(self);
  324. resolve();
  325. }));
  326. };
  327. Crowi.prototype.setupSlackLegacy = async function() {
  328. const self = this;
  329. return new Promise(((resolve, reject) => {
  330. self.slackLegacy = require('../util/slack-legacy')(self);
  331. resolve();
  332. }));
  333. };
  334. Crowi.prototype.setupCsrf = async function() {
  335. const Tokens = require('csrf');
  336. this.tokens = new Tokens();
  337. return Promise.resolve();
  338. };
  339. Crowi.prototype.getTokens = function() {
  340. return this.tokens;
  341. };
  342. Crowi.prototype.start = async function() {
  343. // init CrowiDev
  344. if (this.node_env === 'development') {
  345. const CrowiDev = require('./dev');
  346. this.crowiDev = new CrowiDev(this);
  347. this.crowiDev.init();
  348. }
  349. await this.init();
  350. await this.buildServer();
  351. const { express, configManager } = this;
  352. // setup plugins
  353. this.pluginService = new PluginService(this, express);
  354. this.pluginService.autoDetectAndLoadPlugins();
  355. const server = (this.node_env === 'development') ? this.crowiDev.setupServer(express) : express;
  356. // listen
  357. const serverListening = server.listen(this.port, () => {
  358. logger.info(`[${this.node_env}] Express server is listening on port ${this.port}`);
  359. if (this.node_env === 'development') {
  360. this.crowiDev.setupExpressAfterListening(express);
  361. }
  362. });
  363. // listen for promster
  364. if (configManager.getConfig('crowi', 'promster:isEnabled')) {
  365. const { createServer } = require('@promster/server');
  366. const promsterPort = configManager.getConfig('crowi', 'promster:port');
  367. createServer({ port: promsterPort }).then(() => {
  368. logger.info(`[${this.node_env}] Promster server is listening on port ${promsterPort}`);
  369. });
  370. }
  371. this.socketIoService.attachServer(serverListening);
  372. // setup Express Routes
  373. this.setupRoutesAtLast();
  374. // setup Global Error Handlers
  375. this.setupGlobalErrorHandlers();
  376. return serverListening;
  377. };
  378. Crowi.prototype.buildServer = async function() {
  379. const env = this.node_env;
  380. const express = require('express')();
  381. require('./express-init')(this, express);
  382. // use bunyan
  383. if (env === 'production') {
  384. const expressBunyanLogger = require('express-bunyan-logger');
  385. const logger = loggerFactory('express');
  386. express.use(expressBunyanLogger({
  387. logger,
  388. excludes: ['*'],
  389. }));
  390. }
  391. // use morgan
  392. else {
  393. const morgan = require('morgan');
  394. express.use(morgan('dev'));
  395. }
  396. this.express = express;
  397. };
  398. /**
  399. * setup Express Routes
  400. * !! this must be at last because it includes '/*' route !!
  401. */
  402. Crowi.prototype.setupRoutesAtLast = function() {
  403. require('../routes')(this, this.express);
  404. };
  405. /**
  406. * setup global error handlers
  407. * !! this must be after the Routes setup !!
  408. */
  409. Crowi.prototype.setupGlobalErrorHandlers = function() {
  410. this.express.use(httpErrorHandler);
  411. };
  412. /**
  413. * require API for plugins
  414. *
  415. * @param {string} modulePath relative path from /lib/crowi/index.js
  416. * @return {module}
  417. *
  418. * @memberof Crowi
  419. */
  420. Crowi.prototype.require = function(modulePath) {
  421. return require(modulePath);
  422. };
  423. /**
  424. * setup GlobalNotificationService
  425. */
  426. Crowi.prototype.setUpGlobalNotification = async function() {
  427. const GlobalNotificationService = require('../service/global-notification');
  428. if (this.globalNotificationService == null) {
  429. this.globalNotificationService = new GlobalNotificationService(this);
  430. }
  431. };
  432. /**
  433. * setup UserNotificationService
  434. */
  435. Crowi.prototype.setUpUserNotification = async function() {
  436. const UserNotificationService = require('../service/user-notification');
  437. if (this.userNotificationService == null) {
  438. this.userNotificationService = new UserNotificationService(this);
  439. }
  440. };
  441. /**
  442. * setup SlackNotificationService
  443. */
  444. Crowi.prototype.setUpSlacklNotification = async function() {
  445. const SlackNotificationService = require('../service/slack-notification');
  446. if (this.slackNotificationService == null) {
  447. this.slackNotificationService = new SlackNotificationService(this.configManager);
  448. }
  449. };
  450. /**
  451. * setup XssService
  452. */
  453. Crowi.prototype.setUpXss = async function() {
  454. const XssService = require('../service/xss');
  455. if (this.xssService == null) {
  456. this.xssService = new XssService(this.configManager);
  457. }
  458. };
  459. /**
  460. * setup AclService
  461. */
  462. Crowi.prototype.setUpAcl = async function() {
  463. if (this.aclService == null) {
  464. this.aclService = new AclService(this.configManager);
  465. }
  466. };
  467. /**
  468. * setup CustomizeService
  469. */
  470. Crowi.prototype.setUpCustomize = async function() {
  471. const CustomizeService = require('../service/customize');
  472. if (this.customizeService == null) {
  473. this.customizeService = new CustomizeService(this);
  474. this.customizeService.initCustomCss();
  475. this.customizeService.initCustomTitle();
  476. // add as a message handler
  477. if (this.s2sMessagingService != null) {
  478. this.s2sMessagingService.addMessageHandler(this.customizeService);
  479. }
  480. }
  481. };
  482. /**
  483. * setup AppService
  484. */
  485. Crowi.prototype.setUpApp = async function() {
  486. const AppService = require('../service/app');
  487. if (this.appService == null) {
  488. this.appService = new AppService(this);
  489. // add as a message handler
  490. const isInstalled = this.configManager.getConfig('crowi', 'app:installed');
  491. if (this.s2sMessagingService != null && !isInstalled) {
  492. this.s2sMessagingService.addMessageHandler(this.appService);
  493. }
  494. }
  495. };
  496. /**
  497. * setup FileUploadService
  498. */
  499. Crowi.prototype.setUpFileUpload = async function(isForceUpdate = false) {
  500. if (this.fileUploadService == null || isForceUpdate) {
  501. this.fileUploadService = require('../service/file-uploader')(this);
  502. }
  503. };
  504. /**
  505. * setup FileUploaderSwitchService
  506. */
  507. Crowi.prototype.setUpFileUploaderSwitchService = async function() {
  508. const FileUploaderSwitchService = require('../service/file-uploader-switch');
  509. this.fileUploaderSwitchService = new FileUploaderSwitchService(this);
  510. // add as a message handler
  511. if (this.s2sMessagingService != null) {
  512. this.s2sMessagingService.addMessageHandler(this.fileUploaderSwitchService);
  513. }
  514. };
  515. /**
  516. * setup AttachmentService
  517. */
  518. Crowi.prototype.setupAttachmentService = async function() {
  519. if (this.attachmentService == null) {
  520. this.attachmentService = new AttachmentService(this);
  521. }
  522. };
  523. /**
  524. * setup RestQiitaAPIService
  525. */
  526. Crowi.prototype.setUpRestQiitaAPI = async function() {
  527. const RestQiitaAPIService = require('../service/rest-qiita-API');
  528. if (this.restQiitaAPIService == null) {
  529. this.restQiitaAPIService = new RestQiitaAPIService(this);
  530. }
  531. };
  532. Crowi.prototype.setupUserGroup = async function() {
  533. const UserGroupService = require('../service/user-group');
  534. if (this.userGroupService == null) {
  535. this.userGroupService = new UserGroupService(this);
  536. return this.userGroupService.init();
  537. }
  538. };
  539. Crowi.prototype.setUpGrowiBridge = async function() {
  540. const GrowiBridgeService = require('../service/growi-bridge');
  541. if (this.growiBridgeService == null) {
  542. this.growiBridgeService = new GrowiBridgeService(this);
  543. }
  544. };
  545. Crowi.prototype.setupExport = async function() {
  546. const ExportService = require('../service/export');
  547. if (this.exportService == null) {
  548. this.exportService = new ExportService(this);
  549. }
  550. };
  551. Crowi.prototype.setupImport = async function() {
  552. const ImportService = require('../service/import');
  553. if (this.importService == null) {
  554. this.importService = new ImportService(this);
  555. }
  556. };
  557. Crowi.prototype.setupPageService = async function() {
  558. const PageEventService = require('../service/page');
  559. if (this.pageService == null) {
  560. this.pageService = new PageEventService(this);
  561. }
  562. };
  563. Crowi.prototype.setupSyncPageStatusService = async function() {
  564. const SyncPageStatusService = require('../service/system-events/sync-page-status');
  565. if (this.syncPageStatusService == null) {
  566. this.syncPageStatusService = new SyncPageStatusService(this, this.s2sMessagingService, this.socketIoService);
  567. // add as a message handler
  568. if (this.s2sMessagingService != null) {
  569. this.s2sMessagingService.addMessageHandler(this.syncPageStatusService);
  570. }
  571. }
  572. };
  573. Crowi.prototype.setupSlackBotService = async function() {
  574. const SlackBotService = require('../service/slackbot');
  575. if (this.slackBotService == null) {
  576. this.slackBotService = new SlackBotService(this);
  577. }
  578. // add as a message handler
  579. if (this.s2sMessagingService != null) {
  580. this.s2sMessagingService.addMessageHandler(this.slackBotService);
  581. }
  582. };
  583. module.exports = Crowi;