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.

395 lines
11 KiB

6 years ago
6 years ago
  1. const path = require('path')
  2. const uuid = require('uuid/v4')
  3. /* global WIKI */
  4. module.exports = () => {
  5. WIKI.config.site = {
  6. path: '',
  7. title: 'Wiki.js'
  8. }
  9. WIKI.system = require('./core/system')
  10. // ----------------------------------------
  11. // Load modules
  12. // ----------------------------------------
  13. const bodyParser = require('body-parser')
  14. const compression = require('compression')
  15. const express = require('express')
  16. const favicon = require('serve-favicon')
  17. const http = require('http')
  18. const Promise = require('bluebird')
  19. const fs = require('fs-extra')
  20. const _ = require('lodash')
  21. const cfgHelper = require('./helpers/config')
  22. const crypto = Promise.promisifyAll(require('crypto'))
  23. const pem2jwk = require('pem-jwk').pem2jwk
  24. const semver = require('semver')
  25. // ----------------------------------------
  26. // Define Express App
  27. // ----------------------------------------
  28. let app = express()
  29. app.use(compression())
  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. // HMR (Dev Mode Only)
  47. // ----------------------------------------
  48. if (global.DEV) {
  49. app.use(global.WP_DEV.devMiddleware)
  50. app.use(global.WP_DEV.hotMiddleware)
  51. }
  52. // ----------------------------------------
  53. // Controllers
  54. // ----------------------------------------
  55. app.get('*', async (req, res) => {
  56. let packageObj = await fs.readJson(path.join(WIKI.ROOTPATH, 'package.json'))
  57. res.render('setup', {
  58. packageObj,
  59. telemetryClientID: WIKI.telemetry.cid
  60. })
  61. })
  62. /**
  63. * Finalize
  64. */
  65. app.post('/finalize', async (req, res) => {
  66. WIKI.telemetry.sendEvent('setup', 'finalize')
  67. try {
  68. // Basic checks
  69. if (!semver.satisfies(process.version, '>=10.14')) {
  70. throw new Error('Node.js 10.14.x or later required!')
  71. }
  72. // Upgrade from WIKI.js 1.x?
  73. if (req.body.upgrade) {
  74. await WIKI.system.upgradeFromMongo({
  75. mongoCnStr: cfgHelper.parseConfigValue(req.body.upgMongo)
  76. })
  77. }
  78. // Create directory structure
  79. WIKI.logger.info('Creating data directories...')
  80. const dataPath = path.join(process.cwd(), 'data')
  81. await fs.ensureDir(dataPath)
  82. await fs.emptyDir(path.join(dataPath, 'cache'))
  83. await fs.ensureDir(path.join(dataPath, 'uploads'))
  84. // Set config
  85. _.set(WIKI.config, 'company', '')
  86. _.set(WIKI.config, 'defaultEditor', 'markdown')
  87. _.set(WIKI.config, 'features', {
  88. featurePageRatings: true,
  89. featurePageComments: true,
  90. featurePersonalWikis: true
  91. })
  92. _.set(WIKI.config, 'graphEndpoint', 'https://graph.requarks.io')
  93. _.set(WIKI.config, 'host', 'http://')
  94. _.set(WIKI.config, 'lang', {
  95. code: 'en',
  96. autoUpdate: true,
  97. namespacing: false,
  98. namespaces: []
  99. })
  100. _.set(WIKI.config, 'logo', {
  101. hasLogo: false,
  102. logoIsSquare: false
  103. })
  104. _.set(WIKI.config, 'mail', {
  105. senderName: '',
  106. senderEmail: '',
  107. host: '',
  108. port: 465,
  109. secure: true,
  110. user: '',
  111. pass: '',
  112. useDKIM: false,
  113. dkimDomainName: '',
  114. dkimKeySelector: '',
  115. dkimPrivateKey: ''
  116. })
  117. _.set(WIKI.config, 'public', false)
  118. _.set(WIKI.config, 'seo', {
  119. description: '',
  120. robots: ['index', 'follow'],
  121. ga: ''
  122. })
  123. _.set(WIKI.config, 'sessionSecret', (await crypto.randomBytesAsync(32)).toString('hex'))
  124. _.set(WIKI.config, 'telemetry', {
  125. isEnabled: req.body.telemetry === 'true',
  126. clientId: WIKI.telemetry.cid
  127. })
  128. _.set(WIKI.config, 'theming', {
  129. theme: 'default',
  130. darkMode: false
  131. })
  132. _.set(WIKI.config, 'title', 'Wiki.js')
  133. // Generate certificates
  134. WIKI.logger.info('Generating certificates...')
  135. const certs = crypto.generateKeyPairSync('rsa', {
  136. modulusLength: 2048,
  137. publicKeyEncoding: {
  138. type: 'pkcs1',
  139. format: 'pem'
  140. },
  141. privateKeyEncoding: {
  142. type: 'pkcs1',
  143. format: 'pem',
  144. cipher: 'aes-256-cbc',
  145. passphrase: WIKI.config.sessionSecret
  146. }
  147. })
  148. _.set(WIKI.config, 'certs', {
  149. jwk: pem2jwk(certs.publicKey),
  150. public: certs.publicKey,
  151. private: certs.privateKey
  152. })
  153. // Save config to DB
  154. WIKI.logger.info('Persisting config to DB...')
  155. await WIKI.configSvc.saveToDb([
  156. 'certs',
  157. 'company',
  158. 'defaultEditor',
  159. 'features',
  160. 'graphEndpoint',
  161. 'host',
  162. 'lang',
  163. 'logo',
  164. 'mail',
  165. 'public',
  166. 'seo',
  167. 'sessionSecret',
  168. 'telemetry',
  169. 'theming',
  170. 'title'
  171. ])
  172. // Create default locale
  173. WIKI.logger.info('Installing default locale...')
  174. await WIKI.models.locales.query().insert({
  175. code: 'en',
  176. strings: require('./locales/default.json'),
  177. isRTL: false,
  178. name: 'English',
  179. nativeName: 'English'
  180. })
  181. // Create default groups
  182. WIKI.logger.info('Creating default groups...')
  183. const adminGroup = await WIKI.models.groups.query().insert({
  184. name: 'Administrators',
  185. permissions: JSON.stringify(['manage:system']),
  186. pageRules: JSON.stringify([]),
  187. isSystem: true
  188. })
  189. const guestGroup = await WIKI.models.groups.query().insert({
  190. name: 'Guests',
  191. permissions: JSON.stringify(['read:pages']),
  192. pageRules: JSON.stringify([
  193. { id: 'guest', roles: ['READ', 'AS_READ', 'CM_READ'], match: 'START', deny: false, path: '', locales: [] }
  194. ]),
  195. isSystem: true
  196. })
  197. // Load authentication strategies + enable local
  198. await WIKI.models.authentication.refreshStrategiesFromDisk()
  199. await WIKI.models.authentication.query().patch({ isEnabled: true }).where('key', 'local')
  200. // Load editors + enable default
  201. await WIKI.models.editors.refreshEditorsFromDisk()
  202. await WIKI.models.editors.query().patch({ isEnabled: true }).where('key', 'markdown')
  203. // Load loggers
  204. await WIKI.models.loggers.refreshLoggersFromDisk()
  205. // Load renderers
  206. await WIKI.models.renderers.refreshRenderersFromDisk()
  207. // Load search engines + enable default
  208. await WIKI.models.searchEngines.refreshSearchEnginesFromDisk()
  209. await WIKI.models.searchEngines.query().patch({ isEnabled: true }).where('key', 'db')
  210. // Load storage targets
  211. await WIKI.models.storage.refreshTargetsFromDisk()
  212. // Create root administrator
  213. WIKI.logger.info('Creating root administrator...')
  214. await WIKI.models.users.query().delete().where({
  215. providerKey: 'local',
  216. email: req.body.adminEmail
  217. })
  218. const adminUser = await WIKI.models.users.query().insert({
  219. email: req.body.adminEmail,
  220. provider: 'local',
  221. password: req.body.adminPassword,
  222. name: 'Administrator',
  223. locale: 'en',
  224. defaultEditor: 'markdown',
  225. tfaIsActive: false,
  226. isActive: true,
  227. isVerified: true
  228. })
  229. await adminUser.$relatedQuery('groups').relate(adminGroup.id)
  230. // Create Guest account
  231. WIKI.logger.info('Creating guest account...')
  232. await WIKI.models.users.query().delete().where({
  233. providerKey: 'local',
  234. email: 'guest@example.com'
  235. })
  236. const guestUser = await WIKI.models.users.query().insert({
  237. provider: 'local',
  238. email: 'guest@example.com',
  239. name: 'Guest',
  240. password: '',
  241. locale: 'en',
  242. defaultEditor: 'markdown',
  243. tfaIsActive: false,
  244. isSystem: true,
  245. isActive: true,
  246. isVerified: true
  247. })
  248. await guestUser.$relatedQuery('groups').relate(guestGroup.id)
  249. // Create site nav
  250. WIKI.logger.info('Creating default site navigation')
  251. await WIKI.models.navigation.query().delete().where({ key: 'site' })
  252. await WIKI.models.navigation.query().insert({
  253. key: 'site',
  254. config: [
  255. {
  256. id: uuid(),
  257. icon: 'home',
  258. kind: 'link',
  259. label: 'Home',
  260. target: '/',
  261. targetType: 'home'
  262. }
  263. ]
  264. })
  265. WIKI.logger.info('Setup is complete!')
  266. res.json({
  267. ok: true,
  268. redirectPath: '/',
  269. redirectPort: WIKI.config.port
  270. }).end()
  271. WIKI.config.setup = false
  272. WIKI.logger.info('Stopping Setup...')
  273. WIKI.server.destroy(() => {
  274. WIKI.logger.info('Setup stopped. Starting Wiki.js...')
  275. _.delay(() => {
  276. WIKI.kernel.bootMaster()
  277. }, 1000)
  278. })
  279. } catch (err) {
  280. res.json({ ok: false, error: err.message })
  281. }
  282. })
  283. // ----------------------------------------
  284. // Error handling
  285. // ----------------------------------------
  286. app.use(function (req, res, next) {
  287. var err = new Error('Not Found')
  288. err.status = 404
  289. next(err)
  290. })
  291. app.use(function (err, req, res, next) {
  292. res.status(err.status || 500)
  293. res.send({
  294. message: err.message,
  295. error: WIKI.IS_DEBUG ? err : {}
  296. })
  297. WIKI.logger.error(err.message)
  298. WIKI.telemetry.sendError(err)
  299. })
  300. // ----------------------------------------
  301. // Start HTTP server
  302. // ----------------------------------------
  303. WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
  304. app.set('port', WIKI.config.port)
  305. WIKI.server = http.createServer(app)
  306. WIKI.server.listen(WIKI.config.port, WIKI.config.bindIP)
  307. var openConnections = []
  308. WIKI.server.on('connection', (conn) => {
  309. let key = conn.remoteAddress + ':' + conn.remotePort
  310. openConnections[key] = conn
  311. conn.on('close', () => {
  312. delete openConnections[key]
  313. })
  314. })
  315. WIKI.server.destroy = (cb) => {
  316. WIKI.server.close(cb)
  317. for (let key in openConnections) {
  318. openConnections[key].destroy()
  319. }
  320. }
  321. WIKI.server.on('error', (error) => {
  322. if (error.syscall !== 'listen') {
  323. throw error
  324. }
  325. switch (error.code) {
  326. case 'EACCES':
  327. WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  328. return process.exit(1)
  329. case 'EADDRINUSE':
  330. WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
  331. return process.exit(1)
  332. default:
  333. throw error
  334. }
  335. })
  336. WIKI.server.on('listening', () => {
  337. WIKI.logger.info('HTTP Server: [ RUNNING ]')
  338. WIKI.logger.info('========================================')
  339. WIKI.logger.info(`Browse to http://localhost:${WIKI.config.port}/`)
  340. WIKI.logger.info('========================================')
  341. })
  342. }