index.js 18 KB

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