index.js 19 KB

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