wikijs-fork/server/setup.js

407 lines
13 KiB
JavaScript
Raw Normal View History

2017-10-08 21:21:36 +00:00
const path = require('path')
2017-02-26 23:06:20 +00:00
2017-10-08 21:21:36 +00:00
/* global wiki */
2017-02-26 23:06:20 +00:00
2017-10-08 21:21:36 +00:00
module.exports = () => {
wiki.config.site = {
path: '',
title: 'Wiki.js'
}
wiki.system = require('./modules/system')
2017-02-26 23:06:20 +00:00
// ----------------------------------------
// Load modules
// ----------------------------------------
const bodyParser = require('body-parser')
const compression = require('compression')
const express = require('express')
const favicon = require('serve-favicon')
const http = require('http')
2017-03-05 04:20:22 +00:00
const Promise = require('bluebird')
const fs = Promise.promisifyAll(require('fs-extra'))
2017-03-25 21:03:09 +00:00
const yaml = require('js-yaml')
2017-03-05 04:20:22 +00:00
const _ = require('lodash')
2017-05-15 00:17:08 +00:00
const cfgHelper = require('./helpers/config')
2017-10-23 01:58:07 +00:00
const filesize = require('filesize.js')
const crypto = Promise.promisifyAll(require('crypto'))
2017-02-26 23:06:20 +00:00
// ----------------------------------------
// Define Express App
// ----------------------------------------
2017-10-08 21:21:36 +00:00
let app = express()
2017-02-26 23:06:20 +00:00
app.use(compression())
2017-10-08 21:21:36 +00:00
let server
2017-03-29 02:29:53 +00:00
2017-02-26 23:06:20 +00:00
// ----------------------------------------
// Public Assets
// ----------------------------------------
2017-10-08 21:21:36 +00:00
app.use(favicon(path.join(wiki.ROOTPATH, 'assets', 'favicon.ico')))
app.use(express.static(path.join(wiki.ROOTPATH, 'assets')))
2017-02-26 23:06:20 +00:00
// ----------------------------------------
// View Engine Setup
// ----------------------------------------
2017-10-08 21:21:36 +00:00
app.set('views', path.join(wiki.SERVERPATH, 'views'))
2017-02-26 23:06:20 +00:00
app.set('view engine', 'pug')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
2017-10-08 21:21:36 +00:00
app.locals.config = wiki.config
app.locals.data = wiki.data
2017-02-26 23:06:20 +00:00
app.locals._ = require('lodash')
// ----------------------------------------
// Controllers
// ----------------------------------------
app.get('*', async (req, res) => {
let packageObj = await fs.readJson(path.join(wiki.ROOTPATH, 'package.json'))
2017-12-24 05:34:47 +00:00
res.render('setup', {
packageObj,
telemetryClientID: wiki.telemetry.cid
})
2017-02-26 23:06:20 +00:00
})
2017-03-25 21:03:09 +00:00
/**
* Perform basic system checks
*/
2017-03-05 04:20:22 +00:00
app.post('/syscheck', (req, res) => {
2017-10-23 01:58:07 +00:00
wiki.telemetry.enabled = (req.body.telemetry === true)
wiki.telemetry.sendEvent('setup', 'start')
2017-03-05 04:20:22 +00:00
Promise.mapSeries([
() => {
const semver = require('semver')
2017-11-05 05:36:07 +00:00
if (!semver.satisfies(semver.clean(process.version), '>=8.9.0')) {
throw new Error('Node.js version is too old. Minimum is 8.9.0.')
2017-03-05 04:20:22 +00:00
}
2017-11-05 05:36:07 +00:00
return 'Node.js ' + process.version + ' detected. Minimum is 8.9.0.'
2017-03-05 04:20:22 +00:00
},
() => {
return Promise.try(() => {
require('crypto')
2017-10-08 21:21:36 +00:00
}).catch(err => {
2017-03-05 04:20:22 +00:00
throw new Error('Crypto Node.js module is not available.')
}).return('Node.js Crypto module is available.')
2017-03-05 04:20:22 +00:00
},
() => {
const exec = require('child_process').exec
const semver = require('semver')
return new Promise((resolve, reject) => {
exec('git --version', (err, stdout, stderr) => {
if (err || stdout.length < 3) {
reject(new Error('Git is not installed or not reachable from PATH.'))
}
let gitver = _.head(stdout.match(/[\d]+\.[\d]+(\.[\d]+)?/gi))
if (!gitver || !semver.satisfies(semver.clean(gitver), '>=2.7.4')) {
2017-10-08 21:21:36 +00:00
reject(new Error('Git version is too old. Minimum is 2.7.4.'))
2017-03-05 04:20:22 +00:00
}
2017-10-08 21:21:36 +00:00
resolve('Git ' + gitver + ' detected. Minimum is 2.7.4.')
2017-03-05 04:20:22 +00:00
})
})
},
() => {
const os = require('os')
2017-08-13 18:39:07 +00:00
if (os.totalmem() < 1000 * 1000 * 512) {
throw new Error('Not enough memory. Minimum is 512 MB.')
}
2017-10-23 01:58:07 +00:00
return filesize(os.totalmem()) + ' of system memory available. Minimum is 512 MB.'
},
2017-03-05 04:20:22 +00:00
() => {
let fs = require('fs')
return Promise.try(() => {
2017-10-08 21:21:36 +00:00
fs.accessSync(path.join(wiki.ROOTPATH, 'config.yml'), (fs.constants || fs).W_OK)
}).catch(err => {
2017-03-05 04:20:22 +00:00
throw new Error('config.yml file is not writable by Node.js process or was not created properly.')
}).return('config.yml is writable by the setup process.')
2017-03-05 04:20:22 +00:00
}
], test => test()).then(results => {
res.json({ ok: true, results })
2017-03-05 04:20:22 +00:00
}).catch(err => {
res.json({ ok: false, error: err.message })
})
})
2017-03-25 21:03:09 +00:00
/**
* Check the Git connection
*/
app.post('/gitcheck', (req, res) => {
2017-10-23 01:58:07 +00:00
wiki.telemetry.sendEvent('setup', 'gitcheck')
2017-03-25 21:03:09 +00:00
const exec = require('execa')
2017-03-25 22:21:14 +00:00
const url = require('url')
2017-03-25 21:03:09 +00:00
2017-10-08 21:21:36 +00:00
const dataDir = path.resolve(wiki.ROOTPATH, cfgHelper.parseConfigValue(req.body.pathData))
const gitDir = path.resolve(wiki.ROOTPATH, cfgHelper.parseConfigValue(req.body.pathRepo))
2017-03-25 22:21:14 +00:00
let gitRemoteUrl = ''
if (req.body.gitUseRemote === true) {
2017-05-15 00:17:08 +00:00
let urlObj = url.parse(cfgHelper.parseConfigValue(req.body.gitUrl))
if (req.body.gitAuthType === 'basic') {
urlObj.auth = req.body.gitAuthUser + ':' + req.body.gitAuthPass
}
gitRemoteUrl = url.format(urlObj)
2017-03-25 22:21:14 +00:00
}
Promise.mapSeries([
() => {
return fs.ensureDir(dataDir).then(() => 'Data directory path is valid.')
2017-03-25 22:21:14 +00:00
},
() => {
return fs.ensureDir(gitDir).then(() => 'Git directory path is valid.')
2017-03-25 22:21:14 +00:00
},
() => {
return exec.stdout('git', ['init'], { cwd: gitDir }).then(result => {
return 'Local git repository has been initialized.'
})
},
() => {
if (req.body.gitUseRemote === false) { return false }
return exec.stdout('git', ['config', '--local', 'user.name', 'Wiki'], { cwd: gitDir }).then(result => {
2017-03-25 22:21:14 +00:00
return 'Git Signature Name has been set successfully.'
})
},
() => {
if (req.body.gitUseRemote === false) { return false }
return exec.stdout('git', ['config', '--local', 'user.email', req.body.gitServerEmail], { cwd: gitDir }).then(result => {
2017-03-25 22:21:14 +00:00
return 'Git Signature Name has been set successfully.'
})
},
() => {
if (req.body.gitUseRemote === false) { return false }
2017-03-25 22:21:14 +00:00
return exec.stdout('git', ['config', '--local', '--bool', 'http.sslVerify', req.body.gitAuthSSL], { cwd: gitDir }).then(result => {
return 'Git SSL Verify flag has been set successfully.'
})
},
() => {
if (req.body.gitUseRemote === false) { return false }
if (_.includes(['sshenv', 'sshdb'], req.body.gitAuthType)) {
req.body.gitAuthSSHKey = path.join(dataDir, 'ssh/key.pem')
}
if (_.startsWith(req.body.gitAuthType, 'ssh')) {
2017-03-25 22:21:14 +00:00
return exec.stdout('git', ['config', '--local', 'core.sshCommand', 'ssh -i "' + req.body.gitAuthSSHKey + '" -o StrictHostKeyChecking=no'], { cwd: gitDir }).then(result => {
return 'Git SSH Private Key path has been set successfully.'
})
} else {
return false
}
},
() => {
if (req.body.gitUseRemote === false) { return false }
2017-04-30 04:49:26 +00:00
return exec.stdout('git', ['remote', 'rm', 'origin'], { cwd: gitDir }).catch(err => {
if (_.includes(err.message, 'No such remote') || _.includes(err.message, 'Could not remove')) {
2017-03-25 22:21:14 +00:00
return true
} else {
throw err
}
}).then(() => {
return exec.stdout('git', ['remote', 'add', 'origin', gitRemoteUrl], { cwd: gitDir }).then(result => {
return 'Git Remote was added successfully.'
})
})
},
() => {
if (req.body.gitUseRemote === false) { return false }
2017-03-25 22:21:14 +00:00
return exec.stdout('git', ['pull', 'origin', req.body.gitBranch], { cwd: gitDir }).then(result => {
return 'Git Pull operation successful.'
})
}
], step => { return step() }).then(results => {
return res.json({ ok: true, results: _.without(results, false) })
2017-03-25 21:03:09 +00:00
}).catch(err => {
2017-03-25 22:21:14 +00:00
let errMsg = (err.stderr) ? err.stderr.replace(/(error:|warning:|fatal:)/gi, '').replace(/ \s+/g, ' ') : err.message
res.json({ ok: false, error: errMsg })
2017-03-25 21:03:09 +00:00
})
})
/**
* Finalize
2017-03-25 21:03:09 +00:00
*/
app.post('/finalize', async (req, res) => {
2017-10-23 01:58:07 +00:00
wiki.telemetry.sendEvent('setup', 'finalize')
try {
// Upgrade from Wiki.js 1.x?
if (req.body.upgrade) {
await wiki.system.upgradeFromMongo({
mongoCnStr: cfgHelper.parseConfigValue(req.body.upgMongo)
})
}
// Update config file
2017-12-17 04:41:16 +00:00
wiki.logger.info('Writing config file to disk...')
let confRaw = await fs.readFileAsync(path.join(wiki.ROOTPATH, 'config.yml'), 'utf8')
let conf = yaml.safeLoad(confRaw)
conf.port = req.body.port
conf.paths.repo = req.body.pathRepo
confRaw = yaml.safeDump(conf)
await fs.writeFileAsync(path.join(wiki.ROOTPATH, 'config.yml'), confRaw)
// Populate config namespaces
wiki.config.auth = wiki.config.auth || {}
wiki.config.features = wiki.config.features || {}
wiki.config.git = wiki.config.git || {}
wiki.config.logging = wiki.config.logging || {}
wiki.config.site = wiki.config.site || {}
wiki.config.theme = wiki.config.theme || {}
wiki.config.uploads = wiki.config.uploads || {}
// Site namespace
2017-12-17 04:41:16 +00:00
_.set(wiki.config.site, 'title', req.body.title)
_.set(wiki.config.site, 'path', req.body.path)
_.set(wiki.config.site, 'lang', req.body.lang)
_.set(wiki.config.site, 'rtl', _.includes(wiki.data.rtlLangs, req.body.lang))
_.set(wiki.config.site, 'sessionSecret', (await crypto.randomBytesAsync(32)).toString('hex'))
// Auth namespace
2017-12-17 04:41:16 +00:00
_.set(wiki.config.auth, 'public', req.body.public === 'true')
2017-12-24 05:34:47 +00:00
_.set(wiki.config.auth, 'strategies.local.enabled', true)
2017-12-17 04:41:16 +00:00
_.set(wiki.config.auth, 'strategies.local.allowSelfRegister', req.body.selfRegister === 'true')
// Git namespace
_.set(wiki.config.git, 'enabled', req.body.gitUseRemote === 'true')
if (wiki.config.git.enabled) {
_.set(wiki.config.git, 'url', req.body.gitUrl)
_.set(wiki.config.git, 'branch', req.body.gitBranch)
_.set(wiki.config.git, 'author.defaultEmail', req.body.gitServerEmail)
_.set(wiki.config.git, 'author.useUserEmail', req.body.gitShowUserEmail)
_.set(wiki.config.git, 'sslVerify', req.body.gitAuthSSL === 'true')
_.set(wiki.config.git, 'auth.type', req.body.gitAuthType)
switch (wiki.config.git.auth.type) {
case 'basic':
_.set(wiki.config.git, 'auth.user', req.body.gitAuthUser)
_.set(wiki.config.git, 'auth.pass', req.body.gitAuthPass)
break
case 'ssh':
_.set(wiki.config.git, 'auth.keyPath', req.body.gitAuthSSHKey)
break
case 'sshenv':
_.set(wiki.config.git, 'auth.keyEnv', req.body.gitAuthSSHKeyEnv)
break
case 'sshdb':
_.set(wiki.config.git, 'auth.keyContents', req.body.gitAuthSSHKeyDB)
break
}
}
// Logging namespace
wiki.config.logging.telemetry = (req.body.telemetry === 'true')
2017-12-17 04:41:16 +00:00
// Save config to DB
wiki.logger.info('Persisting config to DB...')
await wiki.configSvc.saveToDb()
// Create root administrator
wiki.logger.info('Creating root administrator...')
await wiki.db.User.upsert({
email: req.body.adminEmail,
provider: 'local',
password: await wiki.db.User.hashPassword(req.body.adminPassword),
name: 'Administrator',
role: 'admin',
tfaIsActive: false
})
2017-12-24 05:34:47 +00:00
wiki.logger.info('Setup is complete!')
res.json({ ok: true })
} catch (err) {
res.json({ ok: false, error: err.message })
}
2017-03-25 21:03:09 +00:00
})
2017-03-29 02:29:53 +00:00
/**
* Restart in normal mode
*/
app.post('/restart', (req, res) => {
res.status(204).end()
2017-10-08 21:21:36 +00:00
/* server.destroy(() => {
2017-03-29 02:29:53 +00:00
spinner.text = 'Setup wizard terminated. Restarting in normal mode...'
_.delay(() => {
const exec = require('execa')
exec.stdout('node', ['wiki', 'start']).then(result => {
spinner.succeed('Wiki.js is now running in normal mode!')
process.exit(0)
})
}, 1000)
2017-10-08 21:21:36 +00:00
}) */
2017-03-29 02:29:53 +00:00
})
2017-02-26 23:06:20 +00:00
// ----------------------------------------
// Error handling
// ----------------------------------------
app.use(function (req, res, next) {
var err = new Error('Not Found')
err.status = 404
next(err)
})
app.use(function (err, req, res, next) {
res.status(err.status || 500)
res.send({
message: err.message,
2017-10-08 21:21:36 +00:00
error: wiki.IS_DEBUG ? err : {}
2017-02-26 23:06:20 +00:00
})
2017-10-08 21:21:36 +00:00
wiki.logger.error(err.message)
2017-10-23 01:58:07 +00:00
wiki.telemetry.sendError(err)
2017-02-26 23:06:20 +00:00
})
// ----------------------------------------
// Start HTTP server
// ----------------------------------------
2017-10-08 21:21:36 +00:00
wiki.logger.info(`HTTP Server on port: ${wiki.config.port}`)
2017-02-26 23:06:20 +00:00
2017-10-08 21:21:36 +00:00
app.set('port', wiki.config.port)
2017-03-29 02:29:53 +00:00
server = http.createServer(app)
2017-10-08 21:21:36 +00:00
server.listen(wiki.config.port)
2017-03-29 02:29:53 +00:00
var openConnections = []
server.on('connection', (conn) => {
let key = conn.remoteAddress + ':' + conn.remotePort
openConnections[key] = conn
conn.on('close', () => {
delete openConnections[key]
})
})
server.destroy = (cb) => {
server.close(cb)
for (let key in openConnections) {
openConnections[key].destroy()
}
}
2017-02-26 23:06:20 +00:00
server.on('error', (error) => {
if (error.syscall !== 'listen') {
throw error
}
switch (error.code) {
case 'EACCES':
2017-10-08 21:21:36 +00:00
wiki.logger.error('Listening on port ' + wiki.config.port + ' requires elevated privileges!')
2017-04-05 02:04:17 +00:00
return process.exit(1)
2017-02-26 23:06:20 +00:00
case 'EADDRINUSE':
2017-10-08 21:21:36 +00:00
wiki.logger.error('Port ' + wiki.config.port + ' is already in use!')
2017-04-05 02:04:17 +00:00
return process.exit(1)
2017-02-26 23:06:20 +00:00
default:
throw error
}
})
server.on('listening', () => {
2017-10-08 21:21:36 +00:00
wiki.logger.info('HTTP Server: RUNNING')
2017-02-26 23:06:20 +00:00
})
}