setup.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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', true)
  244. _.set(WIKI.config, 'graphEndpoint', 'https://graph.requarks.io')
  245. _.set(WIKI.config, 'lang', 'en')
  246. _.set(WIKI.config, 'langAutoUpdate', true)
  247. _.set(WIKI.config, 'langRTL', false)
  248. _.set(WIKI.config, 'paths.content', req.body.pathContent)
  249. _.set(WIKI.config, 'port', req.body.port)
  250. _.set(WIKI.config, 'public', req.body.public === 'true')
  251. _.set(WIKI.config, 'sessionSecret', (await crypto.randomBytesAsync(32)).toString('hex'))
  252. _.set(WIKI.config, 'telemetry', req.body.telemetry === 'true')
  253. _.set(WIKI.config, 'title', req.body.title)
  254. // Save config to DB
  255. WIKI.logger.info('Persisting config to DB...')
  256. await WIKI.db.settings.query().insert([
  257. { key: 'defaultEditor', value: { v: WIKI.config.defaultEditor } },
  258. { key: 'graphEndpoint', value: { v: WIKI.config.graphEndpoint } },
  259. { key: 'lang', value: { v: WIKI.config.lang } },
  260. { key: 'langAutoUpdate', value: { v: WIKI.config.langAutoUpdate } },
  261. { key: 'langRTL', value: { v: WIKI.config.langRTL } },
  262. { key: 'public', value: { v: WIKI.config.public } },
  263. { key: 'sessionSecret', value: { v: WIKI.config.sessionSecret } },
  264. { key: 'telemetry', value: { v: WIKI.config.telemetry } },
  265. { key: 'title', value: { v: WIKI.config.title } }
  266. ])
  267. // Create default locale
  268. WIKI.logger.info('Installing default locale...')
  269. await WIKI.db.locales.query().insert({
  270. code: 'en',
  271. strings: require('./locales/default.json'),
  272. isRTL: false,
  273. name: 'English',
  274. nativeName: 'English'
  275. })
  276. // Load authentication strategies + enable local
  277. await WIKI.db.authentication.refreshStrategiesFromDisk()
  278. await WIKI.db.authentication.query().patch({ isEnabled: true }).where('key', 'local')
  279. // Load editors + enable default
  280. await WIKI.db.editors.refreshEditorsFromDisk()
  281. await WIKI.db.editors.query().patch({ isEnabled: true }).where('key', 'markdown')
  282. // Create root administrator
  283. WIKI.logger.info('Creating root administrator...')
  284. await WIKI.db.users.query().delete().where({
  285. provider: 'local',
  286. email: req.body.adminEmail
  287. })
  288. await WIKI.db.users.query().insert({
  289. email: req.body.adminEmail,
  290. provider: 'local',
  291. password: req.body.adminPassword,
  292. name: 'Administrator',
  293. role: 'admin',
  294. locale: 'en',
  295. defaultEditor: 'markdown',
  296. tfaIsActive: false
  297. })
  298. // Create Guest account
  299. WIKI.logger.info('Creating guest account...')
  300. const guestUsr = await WIKI.db.users.query().findOne({
  301. provider: 'local',
  302. email: 'guest@example.com'
  303. })
  304. if (!guestUsr) {
  305. await WIKI.db.users.query().insert({
  306. provider: 'local',
  307. email: 'guest@example.com',
  308. name: 'Guest',
  309. password: '',
  310. role: 'guest',
  311. locale: 'en',
  312. defaultEditor: 'markdown',
  313. tfaIsActive: false
  314. })
  315. }
  316. WIKI.logger.info('Setup is complete!')
  317. res.json({
  318. ok: true,
  319. redirectPath: WIKI.config.site.path,
  320. redirectPort: WIKI.config.port
  321. }).end()
  322. WIKI.config.setup = false
  323. WIKI.logger.info('Stopping Setup...')
  324. WIKI.server.destroy(() => {
  325. WIKI.logger.info('Setup stopped. Starting Wiki.js...')
  326. _.delay(() => {
  327. WIKI.kernel.bootMaster()
  328. }, 1000)
  329. })
  330. } catch (err) {
  331. res.json({ ok: false, error: err.message })
  332. }
  333. })
  334. // ----------------------------------------
  335. // Error handling
  336. // ----------------------------------------
  337. app.use(function (req, res, next) {
  338. var err = new Error('Not Found')
  339. err.status = 404
  340. next(err)
  341. })
  342. app.use(function (err, req, res, next) {
  343. res.status(err.status || 500)
  344. res.send({
  345. message: err.message,
  346. error: WIKI.IS_DEBUG ? err : {}
  347. })
  348. WIKI.logger.error(err.message)
  349. WIKI.telemetry.sendError(err)
  350. })
  351. // ----------------------------------------
  352. // Start HTTP server
  353. // ----------------------------------------
  354. WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
  355. app.set('port', WIKI.config.port)
  356. WIKI.server = http.createServer(app)
  357. WIKI.server.listen(WIKI.config.port)
  358. var openConnections = []
  359. WIKI.server.on('connection', (conn) => {
  360. let key = conn.remoteAddress + ':' + conn.remotePort
  361. openConnections[key] = conn
  362. conn.on('close', () => {
  363. delete openConnections[key]
  364. })
  365. })
  366. WIKI.server.destroy = (cb) => {
  367. WIKI.server.close(cb)
  368. for (let key in openConnections) {
  369. openConnections[key].destroy()
  370. }
  371. }
  372. WIKI.server.on('error', (error) => {
  373. if (error.syscall !== 'listen') {
  374. throw error
  375. }
  376. switch (error.code) {
  377. case 'EACCES':
  378. WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  379. return process.exit(1)
  380. case 'EADDRINUSE':
  381. WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
  382. return process.exit(1)
  383. default:
  384. throw error
  385. }
  386. })
  387. WIKI.server.on('listening', () => {
  388. WIKI.logger.info('HTTP Server: [ RUNNING ]')
  389. })
  390. }