setup.js 14 KB

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