configure.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. const path = require('path')
  2. /* global wiki */
  3. module.exports = () => {
  4. wiki.config.site = {
  5. path: '',
  6. title: 'Wiki.js'
  7. }
  8. // ----------------------------------------
  9. // Load modules
  10. // ----------------------------------------
  11. const bodyParser = require('body-parser')
  12. const compression = require('compression')
  13. const express = require('express')
  14. const favicon = require('serve-favicon')
  15. const http = require('http')
  16. const Promise = require('bluebird')
  17. const fs = Promise.promisifyAll(require('fs-extra'))
  18. const yaml = require('js-yaml')
  19. const _ = require('lodash')
  20. const cfgHelper = require('./helpers/config')
  21. // ----------------------------------------
  22. // Define Express App
  23. // ----------------------------------------
  24. let app = express()
  25. app.use(compression())
  26. let server
  27. // ----------------------------------------
  28. // Public Assets
  29. // ----------------------------------------
  30. app.use(favicon(path.join(wiki.ROOTPATH, 'assets', 'favicon.ico')))
  31. app.use(express.static(path.join(wiki.ROOTPATH, 'assets')))
  32. // ----------------------------------------
  33. // View Engine Setup
  34. // ----------------------------------------
  35. app.set('views', path.join(wiki.SERVERPATH, 'views'))
  36. app.set('view engine', 'pug')
  37. app.use(bodyParser.json())
  38. app.use(bodyParser.urlencoded({ extended: false }))
  39. app.locals.config = wiki.config
  40. app.locals.data = wiki.data
  41. app.locals._ = require('lodash')
  42. // ----------------------------------------
  43. // Controllers
  44. // ----------------------------------------
  45. app.get('*', (req, res) => {
  46. fs.readJsonAsync(path.join(wiki.ROOTPATH, 'package.json')).then(packageObj => {
  47. res.render('configure/index', { packageObj })
  48. })
  49. })
  50. /**
  51. * Perform basic system checks
  52. */
  53. app.post('/syscheck', (req, res) => {
  54. Promise.mapSeries([
  55. () => {
  56. const semver = require('semver')
  57. if (!semver.satisfies(semver.clean(process.version), '>=6.11.1')) {
  58. throw new Error('Node.js version is too old. Minimum is 6.11.1.')
  59. }
  60. return 'Node.js ' + process.version + ' detected. Minimum is 6.11.1.'
  61. },
  62. () => {
  63. return Promise.try(() => {
  64. require('crypto')
  65. }).catch(err => {
  66. throw new Error('Crypto Node.js module is not available.')
  67. }).return('Node.js Crypto module is available.')
  68. },
  69. () => {
  70. const exec = require('child_process').exec
  71. const semver = require('semver')
  72. return new Promise((resolve, reject) => {
  73. exec('git --version', (err, stdout, stderr) => {
  74. if (err || stdout.length < 3) {
  75. reject(new Error('Git is not installed or not reachable from PATH.'))
  76. }
  77. let gitver = _.head(stdout.match(/[\d]+\.[\d]+(\.[\d]+)?/gi))
  78. if (!gitver || !semver.satisfies(semver.clean(gitver), '>=2.7.4')) {
  79. reject(new Error('Git version is too old. Minimum is 2.7.4.'))
  80. }
  81. resolve('Git ' + gitver + ' detected. Minimum is 2.7.4.')
  82. })
  83. })
  84. },
  85. () => {
  86. const os = require('os')
  87. if (os.totalmem() < 1000 * 1000 * 512) {
  88. throw new Error('Not enough memory. Minimum is 512 MB.')
  89. }
  90. return _.round(os.totalmem() / (1024 * 1024)) + ' MB of system memory available. Minimum is 512 MB.'
  91. },
  92. () => {
  93. let fs = require('fs')
  94. return Promise.try(() => {
  95. fs.accessSync(path.join(wiki.ROOTPATH, 'config.yml'), (fs.constants || fs).W_OK)
  96. }).catch(err => {
  97. throw new Error('config.yml file is not writable by Node.js process or was not created properly.')
  98. }).return('config.yml is writable by the setup process.')
  99. }
  100. ], test => { return test() }).then(results => {
  101. res.json({ ok: true, results })
  102. }).catch(err => {
  103. res.json({ ok: false, error: err.message })
  104. })
  105. })
  106. /**
  107. * Check the Git connection
  108. */
  109. app.post('/gitcheck', (req, res) => {
  110. const exec = require('execa')
  111. const url = require('url')
  112. const dataDir = path.resolve(wiki.ROOTPATH, cfgHelper.parseConfigValue(req.body.pathData))
  113. const gitDir = path.resolve(wiki.ROOTPATH, cfgHelper.parseConfigValue(req.body.pathRepo))
  114. let gitRemoteUrl = ''
  115. if (req.body.gitUseRemote === true) {
  116. let urlObj = url.parse(cfgHelper.parseConfigValue(req.body.gitUrl))
  117. if (req.body.gitAuthType === 'basic') {
  118. urlObj.auth = req.body.gitAuthUser + ':' + req.body.gitAuthPass
  119. }
  120. gitRemoteUrl = url.format(urlObj)
  121. }
  122. Promise.mapSeries([
  123. () => {
  124. return fs.ensureDirAsync(dataDir).return('Data directory path is valid.')
  125. },
  126. () => {
  127. return fs.ensureDirAsync(gitDir).return('Git directory path is valid.')
  128. },
  129. () => {
  130. return exec.stdout('git', ['init'], { cwd: gitDir }).then(result => {
  131. return 'Local git repository has been initialized.'
  132. })
  133. },
  134. () => {
  135. if (req.body.gitUseRemote === false) { return false }
  136. return exec.stdout('git', ['config', '--local', 'user.name', 'Wiki'], { cwd: gitDir }).then(result => {
  137. return 'Git Signature Name has been set successfully.'
  138. })
  139. },
  140. () => {
  141. if (req.body.gitUseRemote === false) { return false }
  142. return exec.stdout('git', ['config', '--local', 'user.email', req.body.gitServerEmail], { cwd: gitDir }).then(result => {
  143. return 'Git Signature Name has been set successfully.'
  144. })
  145. },
  146. () => {
  147. if (req.body.gitUseRemote === false) { return false }
  148. return exec.stdout('git', ['config', '--local', '--bool', 'http.sslVerify', req.body.gitAuthSSL], { cwd: gitDir }).then(result => {
  149. return 'Git SSL Verify flag has been set successfully.'
  150. })
  151. },
  152. () => {
  153. if (req.body.gitUseRemote === false) { return false }
  154. if (req.body.gitAuthType === 'ssh') {
  155. return exec.stdout('git', ['config', '--local', 'core.sshCommand', 'ssh -i "' + req.body.gitAuthSSHKey + '" -o StrictHostKeyChecking=no'], { cwd: gitDir }).then(result => {
  156. return 'Git SSH Private Key path has been set successfully.'
  157. })
  158. } else {
  159. return false
  160. }
  161. },
  162. () => {
  163. if (req.body.gitUseRemote === false) { return false }
  164. return exec.stdout('git', ['remote', 'rm', 'origin'], { cwd: gitDir }).catch(err => {
  165. if (_.includes(err.message, 'No such remote') || _.includes(err.message, 'Could not remove')) {
  166. return true
  167. } else {
  168. throw err
  169. }
  170. }).then(() => {
  171. return exec.stdout('git', ['remote', 'add', 'origin', gitRemoteUrl], { cwd: gitDir }).then(result => {
  172. return 'Git Remote was added successfully.'
  173. })
  174. })
  175. },
  176. () => {
  177. if (req.body.gitUseRemote === false) { return false }
  178. return exec.stdout('git', ['pull', 'origin', req.body.gitBranch], { cwd: gitDir }).then(result => {
  179. return 'Git Pull operation successful.'
  180. })
  181. }
  182. ], step => { return step() }).then(results => {
  183. return res.json({ ok: true, results: _.without(results, false) })
  184. }).catch(err => {
  185. let errMsg = (err.stderr) ? err.stderr.replace(/(error:|warning:|fatal:)/gi, '').replace(/ \s+/g, ' ') : err.message
  186. res.json({ ok: false, error: errMsg })
  187. })
  188. })
  189. /**
  190. * Finalize
  191. */
  192. app.post('/finalize', (req, res) => {
  193. const bcrypt = require('bcryptjs-then')
  194. const crypto = Promise.promisifyAll(require('crypto'))
  195. let mongo = require('mongodb').MongoClient
  196. let parsedMongoConStr = cfgHelper.parseConfigValue(req.body.db)
  197. Promise.join(
  198. new Promise((resolve, reject) => {
  199. mongo.connect(parsedMongoConStr, {
  200. autoReconnect: false,
  201. reconnectTries: 2,
  202. reconnectInterval: 1000,
  203. connectTimeoutMS: 5000,
  204. socketTimeoutMS: 5000
  205. }, (err, db) => {
  206. if (err === null) {
  207. db.createCollection('users', { strict: false }, (err, results) => {
  208. if (err === null) {
  209. bcrypt.hash(req.body.adminPassword).then(adminPwdHash => {
  210. db.collection('users').findOneAndUpdate({
  211. provider: 'local',
  212. email: req.body.adminEmail
  213. }, {
  214. provider: 'local',
  215. email: req.body.adminEmail,
  216. name: 'Administrator',
  217. password: adminPwdHash,
  218. rights: [{
  219. role: 'admin',
  220. path: '/',
  221. exact: false,
  222. deny: false
  223. }],
  224. updatedAt: new Date(),
  225. createdAt: new Date()
  226. }, {
  227. upsert: true,
  228. returnOriginal: false
  229. }, (err, results) => {
  230. if (err === null) {
  231. resolve(true)
  232. } else {
  233. reject(err)
  234. }
  235. db.close()
  236. })
  237. })
  238. } else {
  239. reject(err)
  240. db.close()
  241. }
  242. })
  243. } else {
  244. reject(err)
  245. }
  246. })
  247. }),
  248. fs.readFileAsync(path.join(wiki.ROOTPATH, 'config.yml'), 'utf8').then(confRaw => {
  249. let conf = yaml.safeLoad(confRaw)
  250. conf.title = req.body.title
  251. conf.host = req.body.host
  252. conf.port = req.body.port
  253. conf.paths = {
  254. repo: req.body.pathRepo,
  255. data: req.body.pathData
  256. }
  257. conf.uploads = {
  258. maxImageFileSize: (conf.uploads && _.isNumber(conf.uploads.maxImageFileSize)) ? conf.uploads.maxImageFileSize : 3,
  259. maxOtherFileSize: (conf.uploads && _.isNumber(conf.uploads.maxOtherFileSize)) ? conf.uploads.maxOtherFileSize : 100
  260. }
  261. conf.lang = req.body.lang
  262. conf.public = (req.body.public === true)
  263. if (conf.auth && conf.auth.local) {
  264. conf.auth.local = { enabled: true }
  265. } else {
  266. conf.auth = { local: { enabled: true } }
  267. }
  268. conf.db = req.body.db
  269. if (req.body.gitUseRemote === false) {
  270. conf.git = false
  271. } else {
  272. conf.git = {
  273. url: req.body.gitUrl,
  274. branch: req.body.gitBranch,
  275. auth: {
  276. type: req.body.gitAuthType,
  277. username: req.body.gitAuthUser,
  278. password: req.body.gitAuthPass,
  279. privateKey: req.body.gitAuthSSHKey,
  280. sslVerify: (req.body.gitAuthSSL === true)
  281. },
  282. showUserEmail: (req.body.gitShowUserEmail === true),
  283. serverEmail: req.body.gitServerEmail
  284. }
  285. }
  286. return crypto.randomBytesAsync(32).then(buf => {
  287. conf.sessionSecret = buf.toString('hex')
  288. confRaw = yaml.safeDump(conf)
  289. return fs.writeFileAsync(path.join(wiki.ROOTPATH, 'config.yml'), confRaw)
  290. })
  291. })
  292. ).then(() => {
  293. if (process.env.IS_HEROKU) {
  294. return fs.outputJsonAsync(path.join(wiki.SERVERPATH, 'app/heroku.json'), { configured: true })
  295. } else {
  296. return true
  297. }
  298. }).then(() => {
  299. res.json({ ok: true })
  300. }).catch(err => {
  301. res.json({ ok: false, error: err.message })
  302. })
  303. })
  304. /**
  305. * Restart in normal mode
  306. */
  307. app.post('/restart', (req, res) => {
  308. res.status(204).end()
  309. /* server.destroy(() => {
  310. spinner.text = 'Setup wizard terminated. Restarting in normal mode...'
  311. _.delay(() => {
  312. const exec = require('execa')
  313. exec.stdout('node', ['wiki', 'start']).then(result => {
  314. spinner.succeed('Wiki.js is now running in normal mode!')
  315. process.exit(0)
  316. })
  317. }, 1000)
  318. }) */
  319. })
  320. // ----------------------------------------
  321. // Error handling
  322. // ----------------------------------------
  323. app.use(function (req, res, next) {
  324. var err = new Error('Not Found')
  325. err.status = 404
  326. next(err)
  327. })
  328. app.use(function (err, req, res, next) {
  329. res.status(err.status || 500)
  330. res.send({
  331. message: err.message,
  332. error: wiki.IS_DEBUG ? err : {}
  333. })
  334. wiki.logger.error(err.message)
  335. })
  336. // ----------------------------------------
  337. // Start HTTP server
  338. // ----------------------------------------
  339. wiki.logger.info(`HTTP Server on port: ${wiki.config.port}`)
  340. app.set('port', wiki.config.port)
  341. server = http.createServer(app)
  342. server.listen(wiki.config.port)
  343. var openConnections = []
  344. server.on('connection', (conn) => {
  345. let key = conn.remoteAddress + ':' + conn.remotePort
  346. openConnections[key] = conn
  347. conn.on('close', () => {
  348. delete openConnections[key]
  349. })
  350. })
  351. server.destroy = (cb) => {
  352. server.close(cb)
  353. for (let key in openConnections) {
  354. openConnections[key].destroy()
  355. }
  356. }
  357. server.on('error', (error) => {
  358. if (error.syscall !== 'listen') {
  359. throw error
  360. }
  361. switch (error.code) {
  362. case 'EACCES':
  363. wiki.logger.error('Listening on port ' + wiki.config.port + ' requires elevated privileges!')
  364. return process.exit(1)
  365. case 'EADDRINUSE':
  366. wiki.logger.error('Port ' + wiki.config.port + ' is already in use!')
  367. return process.exit(1)
  368. default:
  369. throw error
  370. }
  371. })
  372. server.on('listening', () => {
  373. wiki.logger.info('HTTP Server: RUNNING')
  374. })
  375. }