index.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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 serverDate = this.configManager.getConfig('crowi', 'autoInstall:serverDate');
  329. const installerService = new InstallerService(this);
  330. try {
  331. installerService.install(firstAdminUserToSave, globalLang ?? 'en_US', serverDate);
  332. }
  333. catch (err) {
  334. logger.warn('Automatic installation failed.', err);
  335. }
  336. };
  337. Crowi.prototype.getTokens = function() {
  338. return this.tokens;
  339. };
  340. Crowi.prototype.start = async function() {
  341. // init CrowiDev
  342. if (this.node_env === 'development') {
  343. const CrowiDev = require('./dev');
  344. this.crowiDev = new CrowiDev(this);
  345. this.crowiDev.init();
  346. }
  347. await this.init();
  348. await this.buildServer();
  349. const { express, configManager } = this;
  350. // setup plugins
  351. this.pluginService = new PluginService(this, express);
  352. await this.pluginService.autoDetectAndLoadPlugins();
  353. const app = (this.node_env === 'development') ? this.crowiDev.setupServer(express) : express;
  354. const httpServer = http.createServer(app);
  355. // setup terminus
  356. this.setupTerminus(httpServer);
  357. // attach to socket.io
  358. this.socketIoService.attachServer(httpServer);
  359. // listen
  360. const serverListening = httpServer.listen(this.port, () => {
  361. logger.info(`[${this.node_env}] Express server is listening on port ${this.port}`);
  362. if (this.node_env === 'development') {
  363. this.crowiDev.setupExpressAfterListening(express);
  364. }
  365. });
  366. // listen for promster
  367. if (configManager.getConfig('crowi', 'promster:isEnabled')) {
  368. const { createServer } = require('@promster/server');
  369. const promsterPort = configManager.getConfig('crowi', 'promster:port');
  370. createServer({ port: promsterPort }).then(() => {
  371. logger.info(`[${this.node_env}] Promster server is listening on port ${promsterPort}`);
  372. });
  373. }
  374. // setup Express Routes
  375. this.setupRoutesAtLast();
  376. // setup Global Error Handlers
  377. this.setupGlobalErrorHandlers();
  378. return serverListening;
  379. };
  380. Crowi.prototype.buildServer = async function() {
  381. const env = this.node_env;
  382. const express = require('express')();
  383. require('./express-init')(this, express);
  384. // use bunyan
  385. if (env === 'production') {
  386. const expressBunyanLogger = require('express-bunyan-logger');
  387. const logger = loggerFactory('express');
  388. express.use(expressBunyanLogger({
  389. logger,
  390. excludes: ['*'],
  391. }));
  392. }
  393. // use morgan
  394. else {
  395. const morgan = require('morgan');
  396. express.use(morgan('dev'));
  397. }
  398. this.express = express;
  399. };
  400. Crowi.prototype.setupTerminus = function(server) {
  401. createTerminus(server, {
  402. signals: ['SIGINT', 'SIGTERM'],
  403. onSignal: async() => {
  404. logger.info('Server is starting cleanup');
  405. await mongoose.disconnect();
  406. return;
  407. },
  408. onShutdown: async() => {
  409. logger.info('Cleanup finished, server is shutting down');
  410. },
  411. });
  412. };
  413. /**
  414. * setup Express Routes
  415. * !! this must be at last because it includes '/*' route !!
  416. */
  417. Crowi.prototype.setupRoutesAtLast = function() {
  418. require('../routes')(this, this.express);
  419. };
  420. /**
  421. * setup global error handlers
  422. * !! this must be after the Routes setup !!
  423. */
  424. Crowi.prototype.setupGlobalErrorHandlers = function() {
  425. this.express.use(httpErrorHandler);
  426. };
  427. /**
  428. * require API for plugins
  429. *
  430. * @param {string} modulePath relative path from /lib/crowi/index.js
  431. * @return {module}
  432. *
  433. * @memberof Crowi
  434. */
  435. Crowi.prototype.require = function(modulePath) {
  436. return require(modulePath);
  437. };
  438. /**
  439. * setup GlobalNotificationService
  440. */
  441. Crowi.prototype.setUpGlobalNotification = async function() {
  442. const GlobalNotificationService = require('../service/global-notification');
  443. if (this.globalNotificationService == null) {
  444. this.globalNotificationService = new GlobalNotificationService(this);
  445. }
  446. };
  447. /**
  448. * setup UserNotificationService
  449. */
  450. Crowi.prototype.setUpUserNotification = async function() {
  451. if (this.userNotificationService == null) {
  452. this.userNotificationService = new UserNotificationService(this);
  453. }
  454. };
  455. /**
  456. * setup XssService
  457. */
  458. Crowi.prototype.setUpXss = async function() {
  459. const XssService = require('../service/xss');
  460. if (this.xssService == null) {
  461. this.xssService = new XssService(this.configManager);
  462. }
  463. };
  464. /**
  465. * setup AclService
  466. */
  467. Crowi.prototype.setUpAcl = async function() {
  468. if (this.aclService == null) {
  469. this.aclService = new AclService(this.configManager);
  470. }
  471. };
  472. /**
  473. * setup CustomizeService
  474. */
  475. Crowi.prototype.setUpCustomize = async function() {
  476. const CustomizeService = require('../service/customize');
  477. if (this.customizeService == null) {
  478. this.customizeService = new CustomizeService(this);
  479. this.customizeService.initCustomCss();
  480. this.customizeService.initCustomTitle();
  481. // add as a message handler
  482. if (this.s2sMessagingService != null) {
  483. this.s2sMessagingService.addMessageHandler(this.customizeService);
  484. }
  485. }
  486. };
  487. /**
  488. * setup AppService
  489. */
  490. Crowi.prototype.setUpApp = async function() {
  491. if (this.appService == null) {
  492. this.appService = new AppService(this);
  493. // add as a message handler
  494. const isInstalled = this.configManager.getConfig('crowi', 'app:installed');
  495. if (this.s2sMessagingService != null && !isInstalled) {
  496. this.s2sMessagingService.addMessageHandler(this.appService);
  497. }
  498. }
  499. };
  500. /**
  501. * setup FileUploadService
  502. */
  503. Crowi.prototype.setUpFileUpload = async function(isForceUpdate = false) {
  504. if (this.fileUploadService == null || isForceUpdate) {
  505. this.fileUploadService = require('../service/file-uploader')(this);
  506. }
  507. };
  508. /**
  509. * setup FileUploaderSwitchService
  510. */
  511. Crowi.prototype.setUpFileUploaderSwitchService = async function() {
  512. const FileUploaderSwitchService = require('../service/file-uploader-switch');
  513. this.fileUploaderSwitchService = new FileUploaderSwitchService(this);
  514. // add as a message handler
  515. if (this.s2sMessagingService != null) {
  516. this.s2sMessagingService.addMessageHandler(this.fileUploaderSwitchService);
  517. }
  518. };
  519. /**
  520. * setup AttachmentService
  521. */
  522. Crowi.prototype.setupAttachmentService = async function() {
  523. if (this.attachmentService == null) {
  524. this.attachmentService = new AttachmentService(this);
  525. }
  526. };
  527. /**
  528. * setup RestQiitaAPIService
  529. */
  530. Crowi.prototype.setUpRestQiitaAPI = async function() {
  531. const RestQiitaAPIService = require('../service/rest-qiita-API');
  532. if (this.restQiitaAPIService == null) {
  533. this.restQiitaAPIService = new RestQiitaAPIService(this);
  534. }
  535. };
  536. Crowi.prototype.setupUserGroup = async function() {
  537. const UserGroupService = require('../service/user-group');
  538. if (this.userGroupService == null) {
  539. this.userGroupService = new UserGroupService(this);
  540. return this.userGroupService.init();
  541. }
  542. };
  543. Crowi.prototype.setUpGrowiBridge = async function() {
  544. const GrowiBridgeService = require('../service/growi-bridge');
  545. if (this.growiBridgeService == null) {
  546. this.growiBridgeService = new GrowiBridgeService(this);
  547. }
  548. };
  549. Crowi.prototype.setupExport = async function() {
  550. const ExportService = require('../service/export');
  551. if (this.exportService == null) {
  552. this.exportService = new ExportService(this);
  553. }
  554. };
  555. Crowi.prototype.setupImport = async function() {
  556. const ImportService = require('../service/import');
  557. if (this.importService == null) {
  558. this.importService = new ImportService(this);
  559. }
  560. };
  561. Crowi.prototype.setupPageService = async function() {
  562. if (this.pageService == null) {
  563. this.pageService = new PageService(this);
  564. }
  565. if (this.pageGrantService == null) {
  566. this.pageGrantService = new PageGrantService(this);
  567. }
  568. };
  569. Crowi.prototype.setupInAppNotificationService = async function() {
  570. const InAppNotificationService = require('../service/in-app-notification');
  571. if (this.inAppNotificationService == null) {
  572. this.inAppNotificationService = new InAppNotificationService(this);
  573. }
  574. };
  575. Crowi.prototype.setupActivityService = async function() {
  576. const ActivityService = require('../service/activity');
  577. if (this.activityService == null) {
  578. this.activityService = new ActivityService(this);
  579. }
  580. };
  581. Crowi.prototype.setupCommentService = async function() {
  582. const CommentService = require('../service/comment');
  583. if (this.commentService == null) {
  584. this.commentService = new CommentService(this);
  585. }
  586. };
  587. Crowi.prototype.setupSyncPageStatusService = async function() {
  588. const SyncPageStatusService = require('../service/system-events/sync-page-status');
  589. if (this.syncPageStatusService == null) {
  590. this.syncPageStatusService = new SyncPageStatusService(this, this.s2sMessagingService, this.socketIoService);
  591. // add as a message handler
  592. if (this.s2sMessagingService != null) {
  593. this.s2sMessagingService.addMessageHandler(this.syncPageStatusService);
  594. }
  595. }
  596. };
  597. Crowi.prototype.setupSlackIntegrationService = async function() {
  598. if (this.slackIntegrationService == null) {
  599. this.slackIntegrationService = new SlackIntegrationService(this);
  600. }
  601. // add as a message handler
  602. if (this.s2sMessagingService != null) {
  603. this.s2sMessagingService.addMessageHandler(this.slackIntegrationService);
  604. }
  605. };
  606. export default Crowi;