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.

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