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.

400 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, 'auth', {
  86. audience: 'urn:wiki.js',
  87. tokenExpiration: '30m',
  88. tokenRenewal: '14d'
  89. })
  90. _.set(WIKI.config, 'company', '')
  91. _.set(WIKI.config, 'features', {
  92. featurePageRatings: true,
  93. featurePageComments: true,
  94. featurePersonalWikis: true
  95. })
  96. _.set(WIKI.config, 'graphEndpoint', 'https://graph.requarks.io')
  97. _.set(WIKI.config, 'host', 'http://')
  98. _.set(WIKI.config, 'lang', {
  99. code: 'en',
  100. autoUpdate: true,
  101. namespacing: false,
  102. namespaces: []
  103. })
  104. _.set(WIKI.config, 'logo', {
  105. hasLogo: false,
  106. logoIsSquare: false
  107. })
  108. _.set(WIKI.config, 'mail', {
  109. senderName: '',
  110. senderEmail: '',
  111. host: '',
  112. port: 465,
  113. secure: true,
  114. user: '',
  115. pass: '',
  116. useDKIM: false,
  117. dkimDomainName: '',
  118. dkimKeySelector: '',
  119. dkimPrivateKey: ''
  120. })
  121. _.set(WIKI.config, 'seo', {
  122. description: '',
  123. robots: ['index', 'follow'],
  124. analyticsService: '',
  125. analyticsId: ''
  126. })
  127. _.set(WIKI.config, 'sessionSecret', (await crypto.randomBytesAsync(32)).toString('hex'))
  128. _.set(WIKI.config, 'telemetry', {
  129. isEnabled: req.body.telemetry === true,
  130. clientId: WIKI.telemetry.cid
  131. })
  132. _.set(WIKI.config, 'theming', {
  133. theme: 'default',
  134. darkMode: false
  135. })
  136. _.set(WIKI.config, 'title', 'Wiki.js')
  137. // Generate certificates
  138. WIKI.logger.info('Generating certificates...')
  139. const certs = crypto.generateKeyPairSync('rsa', {
  140. modulusLength: 2048,
  141. publicKeyEncoding: {
  142. type: 'pkcs1',
  143. format: 'pem'
  144. },
  145. privateKeyEncoding: {
  146. type: 'pkcs1',
  147. format: 'pem',
  148. cipher: 'aes-256-cbc',
  149. passphrase: WIKI.config.sessionSecret
  150. }
  151. })
  152. _.set(WIKI.config, 'certs', {
  153. jwk: pem2jwk(certs.publicKey),
  154. public: certs.publicKey,
  155. private: certs.privateKey
  156. })
  157. // Save config to DB
  158. WIKI.logger.info('Persisting config to DB...')
  159. await WIKI.configSvc.saveToDb([
  160. 'auth',
  161. 'certs',
  162. 'company',
  163. 'features',
  164. 'graphEndpoint',
  165. 'host',
  166. 'lang',
  167. 'logo',
  168. 'mail',
  169. 'seo',
  170. 'sessionSecret',
  171. 'telemetry',
  172. 'theming',
  173. 'title'
  174. ])
  175. // Create default locale
  176. WIKI.logger.info('Installing default locale...')
  177. await WIKI.models.locales.query().insert({
  178. code: 'en',
  179. strings: require('./locales/default.json'),
  180. isRTL: false,
  181. name: 'English',
  182. nativeName: 'English'
  183. })
  184. // Create default groups
  185. WIKI.logger.info('Creating default groups...')
  186. const adminGroup = await WIKI.models.groups.query().insert({
  187. name: 'Administrators',
  188. permissions: JSON.stringify(['manage:system']),
  189. pageRules: JSON.stringify([]),
  190. isSystem: true
  191. })
  192. const guestGroup = await WIKI.models.groups.query().insert({
  193. name: 'Guests',
  194. permissions: JSON.stringify(['read:pages', 'read:assets', 'read:comments']),
  195. pageRules: JSON.stringify([
  196. { id: 'guest', roles: ['read:pages', 'read:assets', 'read:comments'], match: 'START', deny: false, path: '', locales: [] }
  197. ]),
  198. isSystem: true
  199. })
  200. // Load authentication strategies + enable local
  201. await WIKI.models.authentication.refreshStrategiesFromDisk()
  202. await WIKI.models.authentication.query().patch({ isEnabled: true }).where('key', 'local')
  203. // Load editors + enable default
  204. await WIKI.models.editors.refreshEditorsFromDisk()
  205. await WIKI.models.editors.query().patch({ isEnabled: true }).where('key', 'markdown')
  206. // Load loggers
  207. await WIKI.models.loggers.refreshLoggersFromDisk()
  208. // Load renderers
  209. await WIKI.models.renderers.refreshRenderersFromDisk()
  210. // Load search engines + enable default
  211. await WIKI.models.searchEngines.refreshSearchEnginesFromDisk()
  212. await WIKI.models.searchEngines.query().patch({ isEnabled: true }).where('key', 'db')
  213. // Load storage targets
  214. await WIKI.models.storage.refreshTargetsFromDisk()
  215. // Create root administrator
  216. WIKI.logger.info('Creating root administrator...')
  217. await WIKI.models.users.query().delete().where({
  218. providerKey: 'local',
  219. email: req.body.adminEmail
  220. })
  221. const adminUser = await WIKI.models.users.query().insert({
  222. email: req.body.adminEmail,
  223. provider: 'local',
  224. password: req.body.adminPassword,
  225. name: 'Administrator',
  226. locale: 'en',
  227. defaultEditor: 'markdown',
  228. tfaIsActive: false,
  229. isActive: true,
  230. isVerified: true
  231. })
  232. await adminUser.$relatedQuery('groups').relate(adminGroup.id)
  233. // Create Guest account
  234. WIKI.logger.info('Creating guest account...')
  235. await WIKI.models.users.query().delete().where({
  236. providerKey: 'local',
  237. email: 'guest@example.com'
  238. })
  239. const guestUser = await WIKI.models.users.query().insert({
  240. provider: 'local',
  241. email: 'guest@example.com',
  242. name: 'Guest',
  243. password: '',
  244. locale: 'en',
  245. defaultEditor: 'markdown',
  246. tfaIsActive: false,
  247. isSystem: true,
  248. isActive: true,
  249. isVerified: true
  250. })
  251. await guestUser.$relatedQuery('groups').relate(guestGroup.id)
  252. // Create site nav
  253. WIKI.logger.info('Creating default site navigation')
  254. await WIKI.models.navigation.query().delete().where({ key: 'site' })
  255. await WIKI.models.navigation.query().insert({
  256. key: 'site',
  257. config: [
  258. {
  259. id: uuid(),
  260. icon: 'home',
  261. kind: 'link',
  262. label: 'Home',
  263. target: '/',
  264. targetType: 'home'
  265. }
  266. ]
  267. })
  268. WIKI.logger.info('Setup is complete!')
  269. res.json({
  270. ok: true,
  271. redirectPath: '/',
  272. redirectPort: WIKI.config.port
  273. }).end()
  274. WIKI.config.setup = false
  275. WIKI.logger.info('Stopping Setup...')
  276. WIKI.server.destroy(() => {
  277. WIKI.logger.info('Setup stopped. Starting Wiki.js...')
  278. _.delay(() => {
  279. WIKI.kernel.bootMaster()
  280. }, 1000)
  281. })
  282. } catch (err) {
  283. res.json({ ok: false, error: err.message })
  284. }
  285. })
  286. // ----------------------------------------
  287. // Error handling
  288. // ----------------------------------------
  289. app.use(function (req, res, next) {
  290. var err = new Error('Not Found')
  291. err.status = 404
  292. next(err)
  293. })
  294. app.use(function (err, req, res, next) {
  295. res.status(err.status || 500)
  296. res.send({
  297. message: err.message,
  298. error: WIKI.IS_DEBUG ? err : {}
  299. })
  300. WIKI.logger.error(err.message)
  301. WIKI.telemetry.sendError(err)
  302. })
  303. // ----------------------------------------
  304. // Start HTTP server
  305. // ----------------------------------------
  306. WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
  307. app.set('port', WIKI.config.port)
  308. WIKI.server = http.createServer(app)
  309. WIKI.server.listen(WIKI.config.port, WIKI.config.bindIP)
  310. var openConnections = []
  311. WIKI.server.on('connection', (conn) => {
  312. let key = conn.remoteAddress + ':' + conn.remotePort
  313. openConnections[key] = conn
  314. conn.on('close', () => {
  315. delete openConnections[key]
  316. })
  317. })
  318. WIKI.server.destroy = (cb) => {
  319. WIKI.server.close(cb)
  320. for (let key in openConnections) {
  321. openConnections[key].destroy()
  322. }
  323. }
  324. WIKI.server.on('error', (error) => {
  325. if (error.syscall !== 'listen') {
  326. throw error
  327. }
  328. switch (error.code) {
  329. case 'EACCES':
  330. WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  331. return process.exit(1)
  332. case 'EADDRINUSE':
  333. WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
  334. return process.exit(1)
  335. default:
  336. throw error
  337. }
  338. })
  339. WIKI.server.on('listening', () => {
  340. WIKI.logger.info('HTTP Server: [ RUNNING ]')
  341. WIKI.logger.info('🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻')
  342. WIKI.logger.info('')
  343. WIKI.logger.info(`Browse to http://localhost:${WIKI.config.port}/ to complete setup!`)
  344. WIKI.logger.info('')
  345. WIKI.logger.info('🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺')
  346. })
  347. }