index.js 20 KB

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