setup.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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('./modules/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. let server
  30. // ----------------------------------------
  31. // Public Assets
  32. // ----------------------------------------
  33. app.use(favicon(path.join(wiki.ROOTPATH, 'assets', 'favicon.ico')))
  34. app.use(express.static(path.join(wiki.ROOTPATH, 'assets')))
  35. // ----------------------------------------
  36. // View Engine Setup
  37. // ----------------------------------------
  38. app.set('views', path.join(wiki.SERVERPATH, 'views'))
  39. app.set('view engine', 'pug')
  40. app.use(bodyParser.json())
  41. app.use(bodyParser.urlencoded({ extended: false }))
  42. app.locals.config = wiki.config
  43. app.locals.data = wiki.data
  44. app.locals._ = require('lodash')
  45. // ----------------------------------------
  46. // HMR (Dev Mode Only)
  47. // ----------------------------------------
  48. if (global.DEV) {
  49. const webpackDevMiddleware = require('webpack-dev-middleware')
  50. const webpackHotMiddleware = require('webpack-hot-middleware')
  51. app.use(webpackDevMiddleware(global.WP, {
  52. publicPath: global.WPCONFIG.output.publicPath,
  53. logger: wiki.logger
  54. }))
  55. app.use(webpackHotMiddleware(global.WP))
  56. }
  57. // ----------------------------------------
  58. // Controllers
  59. // ----------------------------------------
  60. app.get('*', async (req, res) => {
  61. let packageObj = await fs.readJson(path.join(wiki.ROOTPATH, 'package.json'))
  62. res.render('setup', {
  63. packageObj,
  64. telemetryClientID: wiki.telemetry.cid
  65. })
  66. })
  67. /**
  68. * Perform basic system checks
  69. */
  70. app.post('/syscheck', (req, res) => {
  71. wiki.telemetry.enabled = (req.body.telemetry === true)
  72. wiki.telemetry.sendEvent('setup', 'start')
  73. Promise.mapSeries([
  74. () => {
  75. const semver = require('semver')
  76. if (!semver.satisfies(semver.clean(process.version), '>=8.9.0')) {
  77. throw new Error('Node.js version is too old. Minimum is 8.9.0.')
  78. }
  79. return 'Node.js ' + process.version + ' detected. Minimum is 8.9.0.'
  80. },
  81. () => {
  82. return Promise.try(() => {
  83. require('crypto')
  84. }).catch(err => {
  85. throw new Error('Crypto Node.js module is not available.')
  86. }).return('Node.js Crypto module is available.')
  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('Git ' + gitver + ' detected. Minimum is 2.7.4.')
  101. })
  102. })
  103. },
  104. () => {
  105. const os = require('os')
  106. if (os.totalmem() < 1000 * 1000 * 512) {
  107. throw new Error('Not enough memory. Minimum is 512 MB.')
  108. }
  109. return filesize(os.totalmem()) + ' of system memory available. Minimum is 512 MB.'
  110. },
  111. () => {
  112. let fs = require('fs')
  113. return Promise.try(() => {
  114. fs.accessSync(path.join(wiki.ROOTPATH, 'config.yml'), (fs.constants || fs).W_OK)
  115. }).catch(err => {
  116. throw new Error('config.yml file is not writable by Node.js process or was not created properly.')
  117. }).return('config.yml is writable by the setup process.')
  118. }
  119. ], test => test()).then(results => {
  120. res.json({ ok: true, results })
  121. }).catch(err => {
  122. res.json({ ok: false, error: err.message })
  123. })
  124. })
  125. /**
  126. * Check the Git connection
  127. */
  128. app.post('/gitcheck', (req, res) => {
  129. wiki.telemetry.sendEvent('setup', 'gitcheck')
  130. const exec = require('execa')
  131. const url = require('url')
  132. const dataDir = path.resolve(wiki.ROOTPATH, cfgHelper.parseConfigValue(req.body.pathData))
  133. const gitDir = path.resolve(wiki.ROOTPATH, cfgHelper.parseConfigValue(req.body.pathRepo))
  134. let gitRemoteUrl = ''
  135. if (req.body.gitUseRemote === true) {
  136. let urlObj = url.parse(cfgHelper.parseConfigValue(req.body.gitUrl))
  137. if (req.body.gitAuthType === 'basic') {
  138. urlObj.auth = req.body.gitAuthUser + ':' + req.body.gitAuthPass
  139. }
  140. gitRemoteUrl = url.format(urlObj)
  141. }
  142. Promise.mapSeries([
  143. () => {
  144. return fs.ensureDir(dataDir).then(() => 'Data directory path is valid.')
  145. },
  146. () => {
  147. return fs.ensureDir(gitDir).then(() => 'Git directory path is valid.')
  148. },
  149. () => {
  150. return exec.stdout('git', ['init'], { cwd: gitDir }).then(result => {
  151. return 'Local git repository has been initialized.'
  152. })
  153. },
  154. () => {
  155. if (req.body.gitUseRemote === false) { return false }
  156. return exec.stdout('git', ['config', '--local', 'user.name', 'Wiki'], { cwd: gitDir }).then(result => {
  157. return 'Git Signature Name has been set successfully.'
  158. })
  159. },
  160. () => {
  161. if (req.body.gitUseRemote === false) { return false }
  162. return exec.stdout('git', ['config', '--local', 'user.email', req.body.gitServerEmail], { cwd: gitDir }).then(result => {
  163. return 'Git Signature Name has been set successfully.'
  164. })
  165. },
  166. () => {
  167. if (req.body.gitUseRemote === false) { return false }
  168. return exec.stdout('git', ['config', '--local', '--bool', 'http.sslVerify', req.body.gitAuthSSL], { cwd: gitDir }).then(result => {
  169. return 'Git SSL Verify flag has been set successfully.'
  170. })
  171. },
  172. () => {
  173. if (req.body.gitUseRemote === false) { return false }
  174. if (_.includes(['sshenv', 'sshdb'], req.body.gitAuthType)) {
  175. req.body.gitAuthSSHKey = path.join(dataDir, 'ssh/key.pem')
  176. }
  177. if (_.startsWith(req.body.gitAuthType, 'ssh')) {
  178. return exec.stdout('git', ['config', '--local', 'core.sshCommand', 'ssh -i "' + req.body.gitAuthSSHKey + '" -o StrictHostKeyChecking=no'], { cwd: gitDir }).then(result => {
  179. return 'Git SSH Private Key path has been set successfully.'
  180. })
  181. } else {
  182. return false
  183. }
  184. },
  185. () => {
  186. if (req.body.gitUseRemote === false) { return false }
  187. return exec.stdout('git', ['remote', 'rm', 'origin'], { cwd: gitDir }).catch(err => {
  188. if (_.includes(err.message, 'No such remote') || _.includes(err.message, 'Could not remove')) {
  189. return true
  190. } else {
  191. throw err
  192. }
  193. }).then(() => {
  194. return exec.stdout('git', ['remote', 'add', 'origin', gitRemoteUrl], { cwd: gitDir }).then(result => {
  195. return 'Git Remote was added successfully.'
  196. })
  197. })
  198. },
  199. () => {
  200. if (req.body.gitUseRemote === false) { return false }
  201. return exec.stdout('git', ['pull', 'origin', req.body.gitBranch], { cwd: gitDir }).then(result => {
  202. return 'Git Pull operation successful.'
  203. })
  204. }
  205. ], step => { return step() }).then(results => {
  206. return res.json({ ok: true, results: _.without(results, false) })
  207. }).catch(err => {
  208. let errMsg = (err.stderr) ? err.stderr.replace(/(error:|warning:|fatal:)/gi, '').replace(/ \s+/g, ' ') : err.message
  209. res.json({ ok: false, error: errMsg })
  210. })
  211. })
  212. /**
  213. * Finalize
  214. */
  215. app.post('/finalize', async (req, res) => {
  216. wiki.telemetry.sendEvent('setup', 'finalize')
  217. try {
  218. // Upgrade from Wiki.js 1.x?
  219. if (req.body.upgrade) {
  220. await wiki.system.upgradeFromMongo({
  221. mongoCnStr: cfgHelper.parseConfigValue(req.body.upgMongo)
  222. })
  223. }
  224. // Update config file
  225. wiki.logger.info('Writing config file to disk...')
  226. let confRaw = await fs.readFileAsync(path.join(wiki.ROOTPATH, 'config.yml'), 'utf8')
  227. let conf = yaml.safeLoad(confRaw)
  228. conf.port = req.body.port
  229. conf.paths.repo = req.body.pathRepo
  230. confRaw = yaml.safeDump(conf)
  231. await fs.writeFileAsync(path.join(wiki.ROOTPATH, 'config.yml'), confRaw)
  232. _.set(wiki.config, 'port', req.body.port)
  233. _.set(wiki.config, 'paths.repo', req.body.pathRepo)
  234. // Populate config namespaces
  235. wiki.config.auth = wiki.config.auth || {}
  236. wiki.config.features = wiki.config.features || {}
  237. wiki.config.git = wiki.config.git || {}
  238. wiki.config.logging = wiki.config.logging || {}
  239. wiki.config.site = wiki.config.site || {}
  240. wiki.config.theme = wiki.config.theme || {}
  241. wiki.config.uploads = wiki.config.uploads || {}
  242. // Site namespace
  243. _.set(wiki.config.site, 'title', req.body.title)
  244. _.set(wiki.config.site, 'path', req.body.path)
  245. _.set(wiki.config.site, 'lang', req.body.lang)
  246. _.set(wiki.config.site, 'rtl', _.includes(wiki.data.rtlLangs, req.body.lang))
  247. _.set(wiki.config.site, 'sessionSecret', (await crypto.randomBytesAsync(32)).toString('hex'))
  248. // Auth namespace
  249. _.set(wiki.config.auth, 'public', req.body.public === 'true')
  250. _.set(wiki.config.auth, 'strategies.local.enabled', true)
  251. _.set(wiki.config.auth, 'strategies.local.allowSelfRegister', req.body.selfRegister === 'true')
  252. // Git namespace
  253. _.set(wiki.config.git, 'enabled', req.body.gitUseRemote === 'true')
  254. if (wiki.config.git.enabled) {
  255. _.set(wiki.config.git, 'url', req.body.gitUrl)
  256. _.set(wiki.config.git, 'branch', req.body.gitBranch)
  257. _.set(wiki.config.git, 'author.defaultEmail', req.body.gitServerEmail)
  258. _.set(wiki.config.git, 'author.useUserEmail', req.body.gitShowUserEmail)
  259. _.set(wiki.config.git, 'sslVerify', req.body.gitAuthSSL === 'true')
  260. _.set(wiki.config.git, 'auth.type', req.body.gitAuthType)
  261. switch (wiki.config.git.auth.type) {
  262. case 'basic':
  263. _.set(wiki.config.git, 'auth.user', req.body.gitAuthUser)
  264. _.set(wiki.config.git, 'auth.pass', req.body.gitAuthPass)
  265. break
  266. case 'ssh':
  267. _.set(wiki.config.git, 'auth.keyPath', req.body.gitAuthSSHKey)
  268. break
  269. case 'sshenv':
  270. _.set(wiki.config.git, 'auth.keyEnv', req.body.gitAuthSSHKeyEnv)
  271. break
  272. case 'sshdb':
  273. _.set(wiki.config.git, 'auth.keyContents', req.body.gitAuthSSHKeyDB)
  274. break
  275. }
  276. }
  277. // Logging namespace
  278. wiki.config.logging.telemetry = (req.body.telemetry === 'true')
  279. // Save config to DB
  280. wiki.logger.info('Persisting config to DB...')
  281. await wiki.configSvc.saveToDb()
  282. // Create root administrator
  283. wiki.logger.info('Creating root administrator...')
  284. await wiki.db.User.upsert({
  285. email: req.body.adminEmail,
  286. provider: 'local',
  287. password: await wiki.db.User.hashPassword(req.body.adminPassword),
  288. name: 'Administrator',
  289. role: 'admin',
  290. tfaIsActive: false
  291. })
  292. wiki.logger.info('Setup is complete!')
  293. res.json({
  294. ok: true,
  295. redirectPath: wiki.config.site.path,
  296. redirectPort: wiki.config.port
  297. }).end()
  298. wiki.logger.info('Stopping Setup...')
  299. server.destroy(() => {
  300. wiki.logger.info('Setup stopped. Starting Wiki.js...')
  301. _.delay(() => {
  302. wiki.kernel.bootMaster()
  303. }, 1000)
  304. })
  305. } catch (err) {
  306. res.json({ ok: false, error: err.message })
  307. }
  308. })
  309. // ----------------------------------------
  310. // Error handling
  311. // ----------------------------------------
  312. app.use(function (req, res, next) {
  313. var err = new Error('Not Found')
  314. err.status = 404
  315. next(err)
  316. })
  317. app.use(function (err, req, res, next) {
  318. res.status(err.status || 500)
  319. res.send({
  320. message: err.message,
  321. error: wiki.IS_DEBUG ? err : {}
  322. })
  323. wiki.logger.error(err.message)
  324. wiki.telemetry.sendError(err)
  325. })
  326. // ----------------------------------------
  327. // Start HTTP server
  328. // ----------------------------------------
  329. wiki.logger.info(`HTTP Server on port: ${wiki.config.port}`)
  330. app.set('port', wiki.config.port)
  331. server = http.createServer(app)
  332. server.listen(wiki.config.port)
  333. var openConnections = []
  334. server.on('connection', (conn) => {
  335. let key = conn.remoteAddress + ':' + conn.remotePort
  336. openConnections[key] = conn
  337. conn.on('close', () => {
  338. delete openConnections[key]
  339. })
  340. })
  341. server.destroy = (cb) => {
  342. server.close(cb)
  343. for (let key in openConnections) {
  344. openConnections[key].destroy()
  345. }
  346. }
  347. server.on('error', (error) => {
  348. if (error.syscall !== 'listen') {
  349. throw error
  350. }
  351. switch (error.code) {
  352. case 'EACCES':
  353. wiki.logger.error('Listening on port ' + wiki.config.port + ' requires elevated privileges!')
  354. return process.exit(1)
  355. case 'EADDRINUSE':
  356. wiki.logger.error('Port ' + wiki.config.port + ' is already in use!')
  357. return process.exit(1)
  358. default:
  359. throw error
  360. }
  361. })
  362. server.on('listening', () => {
  363. wiki.logger.info('HTTP Server: RUNNING')
  364. })
  365. }