index.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. const debug = require('debug')('growi:crowi');
  2. const logger = require('@alias/logger')('growi:crowi');
  3. const pkg = require('@root/package.json');
  4. const InterceptorManager = require('@commons/service/interceptor-manager');
  5. const CdnResourcesService = require('@commons/service/cdn-resources-service');
  6. const Xss = require('@commons/service/xss');
  7. const { getMongoUri, mongoOptions } = require('@commons/util/mongoose-utils');
  8. const path = require('path');
  9. const mongoose = require('mongoose');
  10. const models = require('../models');
  11. const PluginService = require('../plugins/plugin.service');
  12. const httpErrorHandler = require('../middlewares/http-error-handler');
  13. const sep = path.sep;
  14. function Crowi(rootdir) {
  15. const self = this;
  16. this.version = pkg.version;
  17. this.runtimeVersions = undefined; // initialized by scanRuntimeVersions()
  18. this.rootDir = rootdir;
  19. this.pluginDir = path.join(this.rootDir, 'node_modules') + sep;
  20. this.publicDir = path.join(this.rootDir, 'public') + sep;
  21. this.libDir = path.join(this.rootDir, 'src/server') + sep;
  22. this.eventsDir = path.join(this.libDir, 'events') + sep;
  23. this.viewsDir = path.join(this.libDir, 'views') + sep;
  24. this.resourceDir = path.join(this.rootDir, 'resource') + sep;
  25. this.localeDir = path.join(this.resourceDir, 'locales') + sep;
  26. this.tmpDir = path.join(this.rootDir, '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(`${self.eventsDir}user`))(this),
  60. page: new (require(`${self.eventsDir}page`))(this),
  61. bookmark: new (require(`${self.eventsDir}bookmark`))(this),
  62. tag: new (require(`${self.eventsDir}tag`))(this),
  63. admin: new (require(`${self.eventsDir}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. const ConfigManager = require('../service/config-manager');
  226. this.configManager = new ConfigManager(this.model('Config'));
  227. return this.configManager.loadConfigs();
  228. };
  229. Crowi.prototype.setupS2sMessagingService = async function() {
  230. const s2sMessagingService = require('../service/s2s-messaging')(this);
  231. if (s2sMessagingService != null) {
  232. s2sMessagingService.subscribe();
  233. this.configManager.setS2sMessagingService(s2sMessagingService);
  234. // add as a message handler
  235. s2sMessagingService.addMessageHandler(this.configManager);
  236. this.s2sMessagingService = s2sMessagingService;
  237. }
  238. };
  239. Crowi.prototype.setupSocketIoService = async function() {
  240. const SocketIoService = require('../service/socket-io');
  241. if (this.socketIoService == null) {
  242. this.socketIoService = new SocketIoService(this);
  243. }
  244. };
  245. Crowi.prototype.setupModels = async function() {
  246. Object.keys(models).forEach((key) => {
  247. return this.model(key, models[key](this));
  248. });
  249. };
  250. Crowi.prototype.scanRuntimeVersions = async function() {
  251. const self = this;
  252. const check = require('check-node-version');
  253. return new Promise((resolve, reject) => {
  254. check((err, result) => {
  255. if (err) {
  256. reject(err);
  257. }
  258. self.runtimeVersions = result;
  259. resolve();
  260. });
  261. });
  262. };
  263. Crowi.prototype.getSlack = function() {
  264. return this.slack;
  265. };
  266. Crowi.prototype.getSlackLegacy = function() {
  267. return this.slackLegacy;
  268. };
  269. Crowi.prototype.getInterceptorManager = function() {
  270. return this.interceptorManager;
  271. };
  272. Crowi.prototype.getGlobalNotificationService = function() {
  273. return this.globalNotificationService;
  274. };
  275. Crowi.prototype.getUserNotificationService = function() {
  276. return this.userNotificationService;
  277. };
  278. Crowi.prototype.getRestQiitaAPIService = function() {
  279. return this.restQiitaAPIService;
  280. };
  281. Crowi.prototype.setupPassport = async function() {
  282. debug('Passport is enabled');
  283. // initialize service
  284. const PassportService = require('../service/passport');
  285. if (this.passportService == null) {
  286. this.passportService = new PassportService(this);
  287. }
  288. this.passportService.setupSerializer();
  289. // setup strategies
  290. try {
  291. this.passportService.setupStrategyById('local');
  292. this.passportService.setupStrategyById('ldap');
  293. this.passportService.setupStrategyById('saml');
  294. this.passportService.setupStrategyById('oidc');
  295. this.passportService.setupStrategyById('basic');
  296. this.passportService.setupStrategyById('google');
  297. this.passportService.setupStrategyById('github');
  298. this.passportService.setupStrategyById('twitter');
  299. }
  300. catch (err) {
  301. logger.error(err);
  302. }
  303. // add as a message handler
  304. if (this.s2sMessagingService != null) {
  305. this.s2sMessagingService.addMessageHandler(this.passportService);
  306. }
  307. return Promise.resolve();
  308. };
  309. Crowi.prototype.setupSearcher = async function() {
  310. const SearchService = require('@server/service/search');
  311. this.searchService = new SearchService(this);
  312. };
  313. Crowi.prototype.setupMailer = async function() {
  314. const MailService = require('@server/service/mail');
  315. this.mailService = new MailService(this);
  316. // add as a message handler
  317. if (this.s2sMessagingService != null) {
  318. this.s2sMessagingService.addMessageHandler(this.mailService);
  319. }
  320. };
  321. Crowi.prototype.setupSlack = async function() {
  322. const self = this;
  323. return new Promise(((resolve, reject) => {
  324. self.slack = require('../util/slack')(self);
  325. resolve();
  326. }));
  327. };
  328. Crowi.prototype.setupSlackLegacy = async function() {
  329. const self = this;
  330. return new Promise(((resolve, reject) => {
  331. self.slackLegacy = require('../util/slack-legacy')(self);
  332. resolve();
  333. }));
  334. };
  335. Crowi.prototype.setupCsrf = async function() {
  336. const Tokens = require('csrf');
  337. this.tokens = new Tokens();
  338. return Promise.resolve();
  339. };
  340. Crowi.prototype.getTokens = function() {
  341. return this.tokens;
  342. };
  343. Crowi.prototype.start = async function() {
  344. // init CrowiDev
  345. if (this.node_env === 'development') {
  346. const CrowiDev = require('./dev');
  347. this.crowiDev = new CrowiDev(this);
  348. this.crowiDev.init();
  349. }
  350. await this.init();
  351. await this.buildServer();
  352. const { express, configManager } = this;
  353. // setup plugins
  354. this.pluginService = new PluginService(this, express);
  355. this.pluginService.autoDetectAndLoadPlugins();
  356. const server = (this.node_env === 'development') ? this.crowiDev.setupServer(express) : express;
  357. // listen
  358. const serverListening = server.listen(this.port, () => {
  359. logger.info(`[${this.node_env}] Express server is listening on port ${this.port}`);
  360. if (this.node_env === 'development') {
  361. this.crowiDev.setupExpressAfterListening(express);
  362. }
  363. });
  364. // listen for promster
  365. if (configManager.getConfig('crowi', 'promster:isEnabled')) {
  366. const { createServer } = require('@promster/server');
  367. const promsterPort = configManager.getConfig('crowi', 'promster:port');
  368. createServer({ port: promsterPort }).then(() => {
  369. logger.info(`[${this.node_env}] Promster server is listening on port ${promsterPort}`);
  370. });
  371. }
  372. this.socketIoService.attachServer(serverListening);
  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 = require('@alias/logger')('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. /**
  400. * setup Express Routes
  401. * !! this must be at last because it includes '/*' route !!
  402. */
  403. Crowi.prototype.setupRoutesAtLast = function() {
  404. require('../routes')(this, this.express);
  405. };
  406. /**
  407. * setup global error handlers
  408. * !! this must be after the Routes setup !!
  409. */
  410. Crowi.prototype.setupGlobalErrorHandlers = function() {
  411. this.express.use(httpErrorHandler);
  412. };
  413. /**
  414. * require API for plugins
  415. *
  416. * @param {string} modulePath relative path from /lib/crowi/index.js
  417. * @return {module}
  418. *
  419. * @memberof Crowi
  420. */
  421. Crowi.prototype.require = function(modulePath) {
  422. return require(modulePath);
  423. };
  424. /**
  425. * setup GlobalNotificationService
  426. */
  427. Crowi.prototype.setUpGlobalNotification = async function() {
  428. const GlobalNotificationService = require('../service/global-notification');
  429. if (this.globalNotificationService == null) {
  430. this.globalNotificationService = new GlobalNotificationService(this);
  431. }
  432. };
  433. /**
  434. * setup UserNotificationService
  435. */
  436. Crowi.prototype.setUpUserNotification = async function() {
  437. const UserNotificationService = require('../service/user-notification');
  438. if (this.userNotificationService == null) {
  439. this.userNotificationService = new UserNotificationService(this);
  440. }
  441. };
  442. /**
  443. * setup SlackNotificationService
  444. */
  445. Crowi.prototype.setUpSlacklNotification = async function() {
  446. const SlackNotificationService = require('../service/slack-notification');
  447. if (this.slackNotificationService == null) {
  448. this.slackNotificationService = new SlackNotificationService(this.configManager);
  449. }
  450. };
  451. /**
  452. * setup XssService
  453. */
  454. Crowi.prototype.setUpXss = async function() {
  455. const XssService = require('../service/xss');
  456. if (this.xssService == null) {
  457. this.xssService = new XssService(this.configManager);
  458. }
  459. };
  460. /**
  461. * setup AclService
  462. */
  463. Crowi.prototype.setUpAcl = async function() {
  464. const AclService = require('../service/acl');
  465. if (this.aclService == null) {
  466. this.aclService = new AclService(this.configManager);
  467. }
  468. };
  469. /**
  470. * setup CustomizeService
  471. */
  472. Crowi.prototype.setUpCustomize = async function() {
  473. const CustomizeService = require('../service/customize');
  474. if (this.customizeService == null) {
  475. this.customizeService = new CustomizeService(this);
  476. this.customizeService.initCustomCss();
  477. this.customizeService.initCustomTitle();
  478. // add as a message handler
  479. if (this.s2sMessagingService != null) {
  480. this.s2sMessagingService.addMessageHandler(this.customizeService);
  481. }
  482. }
  483. };
  484. /**
  485. * setup AppService
  486. */
  487. Crowi.prototype.setUpApp = async function() {
  488. const AppService = require('../service/app');
  489. if (this.appService == null) {
  490. this.appService = new AppService(this);
  491. // add as a message handler
  492. const isInstalled = this.configManager.getConfig('crowi', 'app:installed');
  493. if (this.s2sMessagingService != null && !isInstalled) {
  494. this.s2sMessagingService.addMessageHandler(this.appService);
  495. }
  496. }
  497. };
  498. /**
  499. * setup FileUploadService
  500. */
  501. Crowi.prototype.setUpFileUpload = async function(isForceUpdate = false) {
  502. if (this.fileUploadService == null || isForceUpdate) {
  503. this.fileUploadService = require('../service/file-uploader')(this);
  504. }
  505. };
  506. /**
  507. * setup FileUploaderSwitchService
  508. */
  509. Crowi.prototype.setUpFileUploaderSwitchService = async function() {
  510. const FileUploaderSwitchService = require('../service/file-uploader-switch');
  511. this.fileUploaderSwitchService = new FileUploaderSwitchService(this);
  512. // add as a message handler
  513. if (this.s2sMessagingService != null) {
  514. this.s2sMessagingService.addMessageHandler(this.fileUploaderSwitchService);
  515. }
  516. };
  517. /**
  518. * setup AttachmentService
  519. */
  520. Crowi.prototype.setupAttachmentService = async function() {
  521. const AttachmentService = require('../service/attachment');
  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. const PageEventService = require('../service/page');
  562. if (this.pageService == null) {
  563. this.pageService = new PageEventService(this);
  564. }
  565. };
  566. Crowi.prototype.setupSyncPageStatusService = async function() {
  567. const SyncPageStatusService = require('../service/system-events/sync-page-status');
  568. if (this.syncPageStatusService == null) {
  569. this.syncPageStatusService = new SyncPageStatusService(this, this.s2sMessagingService, this.socketIoService);
  570. // add as a message handler
  571. if (this.s2sMessagingService != null) {
  572. this.s2sMessagingService.addMessageHandler(this.syncPageStatusService);
  573. }
  574. }
  575. };
  576. Crowi.prototype.setupSlackBotService = async function() {
  577. const SlackBotService = require('../service/slackbot');
  578. if (this.slackBotService == null) {
  579. this.slackBotService = new SlackBotService(this);
  580. }
  581. // add as a message handler
  582. if (this.s2sMessagingService != null) {
  583. this.s2sMessagingService.addMessageHandler(this.slackBotService);
  584. }
  585. };
  586. module.exports = Crowi;