index.js 20 KB

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