You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

443 lines
14 KiB

  1. const path = require('path')
  2. /* global WIKI */
  3. module.exports = () => {
  4. WIKI.config.site = {
  5. path: '',
  6. title: 'Wiki.js'
  7. }
  8. WIKI.system = require('./core/system')
  9. // ----------------------------------------
  10. // Load modules
  11. // ----------------------------------------
  12. const bodyParser = require('body-parser')
  13. const compression = require('compression')
  14. const express = require('express')
  15. const favicon = require('serve-favicon')
  16. const http = require('http')
  17. const Promise = require('bluebird')
  18. const fs = Promise.promisifyAll(require('fs-extra'))
  19. const yaml = require('js-yaml')
  20. const _ = require('lodash')
  21. const cfgHelper = require('./helpers/config')
  22. const filesize = require('filesize.js')
  23. const crypto = Promise.promisifyAll(require('crypto'))
  24. // ----------------------------------------
  25. // Define Express App
  26. // ----------------------------------------
  27. let app = express()
  28. app.use(compression())
  29. // ----------------------------------------
  30. // Public Assets
  31. // ----------------------------------------
  32. app.use(favicon(path.join(WIKI.ROOTPATH, 'assets', 'favicon.ico')))
  33. app.use(express.static(path.join(WIKI.ROOTPATH, 'assets')))
  34. // ----------------------------------------
  35. // View Engine Setup
  36. // ----------------------------------------
  37. app.set('views', path.join(WIKI.SERVERPATH, 'views'))
  38. app.set('view engine', 'pug')
  39. app.use(bodyParser.json())
  40. app.use(bodyParser.urlencoded({ extended: false }))
  41. app.locals.config = WIKI.config
  42. app.locals.data = WIKI.data
  43. app.locals._ = require('lodash')
  44. // ----------------------------------------
  45. // HMR (Dev Mode Only)
  46. // ----------------------------------------
  47. if (global.DEV) {
  48. app.use(global.WP_DEV.devMiddleware)
  49. app.use(global.WP_DEV.hotMiddleware)
  50. }
  51. // ----------------------------------------
  52. // Controllers
  53. // ----------------------------------------
  54. app.get('*', async (req, res) => {
  55. let packageObj = await fs.readJson(path.join(WIKI.ROOTPATH, 'package.json'))
  56. res.render('main/setup', {
  57. packageObj,
  58. telemetryClientID: WIKI.telemetry.cid
  59. })
  60. })
  61. /**
  62. * Perform basic system checks
  63. */
  64. app.post('/syscheck', (req, res) => {
  65. WIKI.telemetry.enabled = (req.body.telemetry === true)
  66. WIKI.telemetry.sendEvent('setup', 'start')
  67. Promise.mapSeries([
  68. () => {
  69. const semver = require('semver')
  70. if (!semver.satisfies(semver.clean(process.version), '>=8.9.0')) {
  71. throw new Error('Node.js version is too old. Minimum is 8.9.0.')
  72. }
  73. return {
  74. title: 'Node.js ' + process.version + ' detected.',
  75. subtitle: ' Minimum is 8.9.0.'
  76. }
  77. },
  78. () => {
  79. return Promise.try(() => {
  80. require('crypto')
  81. }).catch(err => {
  82. throw new Error('Crypto Node.js module is not available.')
  83. }).return({
  84. title: 'Node.js Crypto module is available.',
  85. subtitle: 'Crypto module is required.'
  86. })
  87. },
  88. () => {
  89. const exec = require('child_process').exec
  90. const semver = require('semver')
  91. return new Promise((resolve, reject) => {
  92. exec('git --version', (err, stdout, stderr) => {
  93. if (err || stdout.length < 3) {
  94. reject(new Error('Git is not installed or not reachable from PATH.'))
  95. }
  96. let gitver = _.head(stdout.match(/[\d]+\.[\d]+(\.[\d]+)?/gi))
  97. if (!gitver || !semver.satisfies(semver.clean(gitver), '>=2.7.4')) {
  98. reject(new Error('Git version is too old. Minimum is 2.7.4.'))
  99. }
  100. resolve({
  101. title: 'Git ' + gitver + ' detected.',
  102. subtitle: 'Minimum is 2.7.4.'
  103. })
  104. })
  105. })
  106. },
  107. () => {
  108. const os = require('os')
  109. if (os.totalmem() < 1000 * 1000 * 768) {
  110. throw new Error('Not enough memory. Minimum is 768 MB.')
  111. }
  112. return {
  113. title: filesize(os.totalmem()) + ' of system memory available.',
  114. subtitle: 'Minimum is 768 MB.'
  115. }
  116. },
  117. () => {
  118. let fs = require('fs')
  119. return Promise.try(() => {
  120. fs.accessSync(path.join(WIKI.ROOTPATH, 'config.yml'), (fs.constants || fs).W_OK)
  121. }).catch(err => {
  122. throw new Error('config.yml file is not writable by Node.js process or was not created properly.')
  123. }).return({
  124. title: 'config.yml is writable by the setup process.',
  125. subtitle: 'Setup will write to this file.'
  126. })
  127. }
  128. ], test => test()).then(results => {
  129. res.json({ ok: true, results })
  130. }).catch(err => {
  131. res.json({ ok: false, error: err.message })
  132. })
  133. })
  134. /**
  135. * Check the Git connection
  136. */
  137. app.post('/gitcheck', (req, res) => {
  138. WIKI.telemetry.sendEvent('setup', 'gitcheck')
  139. const exec = require('execa')
  140. const url = require('url')
  141. const dataDir = path.resolve(WIKI.ROOTPATH, cfgHelper.parseConfigValue(req.body.pathData))
  142. const gitDir = path.resolve(WIKI.ROOTPATH, cfgHelper.parseConfigValue(req.body.pathRepo))
  143. let gitRemoteUrl = ''
  144. if (req.body.gitUseRemote === true) {
  145. let urlObj = url.parse(cfgHelper.parseConfigValue(req.body.gitUrl))
  146. if (req.body.gitAuthType === 'basic') {
  147. urlObj.auth = req.body.gitAuthUser + ':' + req.body.gitAuthPass
  148. }
  149. gitRemoteUrl = url.format(urlObj)
  150. }
  151. Promise.mapSeries([
  152. () => {
  153. return fs.ensureDir(dataDir).then(() => 'Data directory path is valid.')
  154. },
  155. () => {
  156. return fs.ensureDir(gitDir).then(() => 'Git directory path is valid.')
  157. },
  158. () => {
  159. return exec.stdout('git', ['init'], { cwd: gitDir }).then(result => {
  160. return 'Local git repository has been initialized.'
  161. })
  162. },
  163. () => {
  164. if (req.body.gitUseRemote === false) { return false }
  165. return exec.stdout('git', ['config', '--local', 'user.name', 'Wiki'], { cwd: gitDir }).then(result => {
  166. return 'Git Signature Name has been set successfully.'
  167. })
  168. },
  169. () => {
  170. if (req.body.gitUseRemote === false) { return false }
  171. return exec.stdout('git', ['config', '--local', 'user.email', req.body.gitServerEmail], { cwd: gitDir }).then(result => {
  172. return 'Git Signature Name has been set successfully.'
  173. })
  174. },
  175. () => {
  176. if (req.body.gitUseRemote === false) { return false }
  177. return exec.stdout('git', ['config', '--local', '--bool', 'http.sslVerify', req.body.gitAuthSSL], { cwd: gitDir }).then(result => {
  178. return 'Git SSL Verify flag has been set successfully.'
  179. })
  180. },
  181. () => {
  182. if (req.body.gitUseRemote === false) { return false }
  183. if (_.includes(['sshenv', 'sshdb'], req.body.gitAuthType)) {
  184. req.body.gitAuthSSHKey = path.join(dataDir, 'ssh/key.pem')
  185. }
  186. if (_.startsWith(req.body.gitAuthType, 'ssh')) {
  187. return exec.stdout('git', ['config', '--local', 'core.sshCommand', 'ssh -i "' + req.body.gitAuthSSHKey + '" -o StrictHostKeyChecking=no'], { cwd: gitDir }).then(result => {
  188. return 'Git SSH Private Key path has been set successfully.'
  189. })
  190. } else {
  191. return false
  192. }
  193. },
  194. () => {
  195. if (req.body.gitUseRemote === false) { return false }
  196. return exec.stdout('git', ['remote', 'rm', 'origin'], { cwd: gitDir }).catch(err => {
  197. if (_.includes(err.message, 'No such remote') || _.includes(err.message, 'Could not remove')) {
  198. return true
  199. } else {
  200. throw err
  201. }
  202. }).then(() => {
  203. return exec.stdout('git', ['remote', 'add', 'origin', gitRemoteUrl], { cwd: gitDir }).then(result => {
  204. return 'Git Remote was added successfully.'
  205. })
  206. })
  207. },
  208. () => {
  209. if (req.body.gitUseRemote === false) { return false }
  210. return exec.stdout('git', ['pull', 'origin', req.body.gitBranch], { cwd: gitDir }).then(result => {
  211. return 'Git Pull operation successful.'
  212. })
  213. }
  214. ], step => { return step() }).then(results => {
  215. return res.json({ ok: true, results: _.without(results, false) })
  216. }).catch(err => {
  217. let errMsg = (err.stderr) ? err.stderr.replace(/(error:|warning:|fatal:)/gi, '').replace(/ \s+/g, ' ') : err.message
  218. res.json({ ok: false, error: errMsg })
  219. })
  220. })
  221. /**
  222. * Finalize
  223. */
  224. app.post('/finalize', async (req, res) => {
  225. WIKI.telemetry.sendEvent('setup', 'finalize')
  226. try {
  227. // Upgrade from WIKI.js 1.x?
  228. if (req.body.upgrade) {
  229. await WIKI.system.upgradeFromMongo({
  230. mongoCnStr: cfgHelper.parseConfigValue(req.body.upgMongo)
  231. })
  232. }
  233. // Update config file
  234. WIKI.logger.info('Writing config file to disk...')
  235. let confRaw = await fs.readFileAsync(path.join(WIKI.ROOTPATH, 'config.yml'), 'utf8')
  236. let conf = yaml.safeLoad(confRaw)
  237. conf.port = req.body.port
  238. conf.paths.data = req.body.pathData
  239. conf.paths.content = req.body.pathContent
  240. confRaw = yaml.safeDump(conf)
  241. await fs.writeFileAsync(path.join(WIKI.ROOTPATH, 'config.yml'), confRaw)
  242. // Set config
  243. _.set(WIKI.config, 'defaultEditor', 'markdown')
  244. _.set(WIKI.config, 'graphEndpoint', 'https://graph.requarks.io')
  245. _.set(WIKI.config, 'lang.code', 'en')
  246. _.set(WIKI.config, 'lang.autoUpdate', true)
  247. _.set(WIKI.config, 'lang.namespacing', false)
  248. _.set(WIKI.config, 'lang.namespaces', [])
  249. _.set(WIKI.config, 'paths.content', req.body.pathContent)
  250. _.set(WIKI.config, 'paths.data', req.body.pathData)
  251. _.set(WIKI.config, 'port', req.body.port)
  252. _.set(WIKI.config, 'public', req.body.public === 'true')
  253. _.set(WIKI.config, 'sessionSecret', (await crypto.randomBytesAsync(32)).toString('hex'))
  254. _.set(WIKI.config, 'telemetry.isEnabled', req.body.telemetry === 'true')
  255. _.set(WIKI.config, 'telemetry.clientId', WIKI.telemetry.cid)
  256. _.set(WIKI.config, 'title', req.body.title)
  257. // Save config to DB
  258. WIKI.logger.info('Persisting config to DB...')
  259. await WIKI.configSvc.saveToDb([
  260. 'defaultEditor',
  261. 'graphEndpoint',
  262. 'lang',
  263. 'public',
  264. 'sessionSecret',
  265. 'telemetry',
  266. 'title'
  267. ])
  268. // Create default locale
  269. WIKI.logger.info('Installing default locale...')
  270. await WIKI.db.locales.query().insert({
  271. code: 'en',
  272. strings: require('./locales/default.json'),
  273. isRTL: false,
  274. name: 'English',
  275. nativeName: 'English'
  276. })
  277. // Load authentication strategies + enable local
  278. await WIKI.db.authentication.refreshStrategiesFromDisk()
  279. await WIKI.db.authentication.query().patch({ isEnabled: true }).where('key', 'local')
  280. // Load editors + enable default
  281. await WIKI.db.editors.refreshEditorsFromDisk()
  282. await WIKI.db.editors.query().patch({ isEnabled: true }).where('key', 'markdown')
  283. // Create root administrator
  284. WIKI.logger.info('Creating root administrator...')
  285. await WIKI.db.users.query().delete().where({
  286. provider: 'local',
  287. email: req.body.adminEmail
  288. })
  289. await WIKI.db.users.query().insert({
  290. email: req.body.adminEmail,
  291. provider: 'local',
  292. password: req.body.adminPassword,
  293. name: 'Administrator',
  294. role: 'admin',
  295. locale: 'en',
  296. defaultEditor: 'markdown',
  297. tfaIsActive: false
  298. })
  299. // Create Guest account
  300. WIKI.logger.info('Creating guest account...')
  301. const guestUsr = await WIKI.db.users.query().findOne({
  302. provider: 'local',
  303. email: 'guest@example.com'
  304. })
  305. if (!guestUsr) {
  306. await WIKI.db.users.query().insert({
  307. provider: 'local',
  308. email: 'guest@example.com',
  309. name: 'Guest',
  310. password: '',
  311. role: 'guest',
  312. locale: 'en',
  313. defaultEditor: 'markdown',
  314. tfaIsActive: false
  315. })
  316. }
  317. WIKI.logger.info('Setup is complete!')
  318. res.json({
  319. ok: true,
  320. redirectPath: WIKI.config.site.path,
  321. redirectPort: WIKI.config.port
  322. }).end()
  323. WIKI.config.setup = false
  324. WIKI.logger.info('Stopping Setup...')
  325. WIKI.server.destroy(() => {
  326. WIKI.logger.info('Setup stopped. Starting Wiki.js...')
  327. _.delay(() => {
  328. WIKI.kernel.bootMaster()
  329. }, 1000)
  330. })
  331. } catch (err) {
  332. res.json({ ok: false, error: err.message })
  333. }
  334. })
  335. // ----------------------------------------
  336. // Error handling
  337. // ----------------------------------------
  338. app.use(function (req, res, next) {
  339. var err = new Error('Not Found')
  340. err.status = 404
  341. next(err)
  342. })
  343. app.use(function (err, req, res, next) {
  344. res.status(err.status || 500)
  345. res.send({
  346. message: err.message,
  347. error: WIKI.IS_DEBUG ? err : {}
  348. })
  349. WIKI.logger.error(err.message)
  350. WIKI.telemetry.sendError(err)
  351. })
  352. // ----------------------------------------
  353. // Start HTTP server
  354. // ----------------------------------------
  355. WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
  356. app.set('port', WIKI.config.port)
  357. WIKI.server = http.createServer(app)
  358. WIKI.server.listen(WIKI.config.port)
  359. var openConnections = []
  360. WIKI.server.on('connection', (conn) => {
  361. let key = conn.remoteAddress + ':' + conn.remotePort
  362. openConnections[key] = conn
  363. conn.on('close', () => {
  364. delete openConnections[key]
  365. })
  366. })
  367. WIKI.server.destroy = (cb) => {
  368. WIKI.server.close(cb)
  369. for (let key in openConnections) {
  370. openConnections[key].destroy()
  371. }
  372. }
  373. WIKI.server.on('error', (error) => {
  374. if (error.syscall !== 'listen') {
  375. throw error
  376. }
  377. switch (error.code) {
  378. case 'EACCES':
  379. WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  380. return process.exit(1)
  381. case 'EADDRINUSE':
  382. WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
  383. return process.exit(1)
  384. default:
  385. throw error
  386. }
  387. })
  388. WIKI.server.on('listening', () => {
  389. WIKI.logger.info('HTTP Server: [ RUNNING ]')
  390. })
  391. }