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.

426 lines
12 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
  1. const path = require('path')
  2. const uuid = require('uuid/v4')
  3. const bodyParser = require('body-parser')
  4. const compression = require('compression')
  5. const express = require('express')
  6. const favicon = require('serve-favicon')
  7. const http = require('http')
  8. const https = require('https')
  9. const Promise = require('bluebird')
  10. const fs = require('fs-extra')
  11. const _ = require('lodash')
  12. const cfgHelper = require('./helpers/config')
  13. const crypto = Promise.promisifyAll(require('crypto'))
  14. const pem2jwk = require('pem-jwk').pem2jwk
  15. const semver = require('semver')
  16. /* global WIKI */
  17. module.exports = () => {
  18. WIKI.config.site = {
  19. path: '',
  20. title: 'Wiki.js'
  21. }
  22. WIKI.system = require('./core/system')
  23. // ----------------------------------------
  24. // Define Express App
  25. // ----------------------------------------
  26. let app = express()
  27. app.use(compression())
  28. // ----------------------------------------
  29. // Public Assets
  30. // ----------------------------------------
  31. app.use(favicon(path.join(WIKI.ROOTPATH, 'assets', 'favicon.ico')))
  32. app.use(express.static(path.join(WIKI.ROOTPATH, 'assets')))
  33. // ----------------------------------------
  34. // View Engine Setup
  35. // ----------------------------------------
  36. app.set('views', path.join(WIKI.SERVERPATH, 'views'))
  37. app.set('view engine', 'pug')
  38. app.use(bodyParser.json())
  39. app.use(bodyParser.urlencoded({ extended: false }))
  40. app.locals.config = WIKI.config
  41. app.locals.data = WIKI.data
  42. app.locals._ = require('lodash')
  43. // ----------------------------------------
  44. // HMR (Dev Mode Only)
  45. // ----------------------------------------
  46. if (global.DEV) {
  47. app.use(global.WP_DEV.devMiddleware)
  48. app.use(global.WP_DEV.hotMiddleware)
  49. }
  50. // ----------------------------------------
  51. // Controllers
  52. // ----------------------------------------
  53. app.get('*', async (req, res) => {
  54. let packageObj = await fs.readJson(path.join(WIKI.ROOTPATH, 'package.json'))
  55. res.render('setup', { packageObj })
  56. })
  57. /**
  58. * Finalize
  59. */
  60. app.post('/finalize', async (req, res) => {
  61. try {
  62. // Set config
  63. _.set(WIKI.config, 'auth', {
  64. audience: 'urn:wiki.js',
  65. tokenExpiration: '30m',
  66. tokenRenewal: '14d'
  67. })
  68. _.set(WIKI.config, 'company', '')
  69. _.set(WIKI.config, 'features', {
  70. featurePageRatings: true,
  71. featurePageComments: true,
  72. featurePersonalWikis: true
  73. })
  74. _.set(WIKI.config, 'graphEndpoint', 'https://graph.requarks.io')
  75. _.set(WIKI.config, 'host', req.body.siteUrl)
  76. _.set(WIKI.config, 'lang', {
  77. code: 'en',
  78. autoUpdate: true,
  79. namespacing: false,
  80. namespaces: []
  81. })
  82. _.set(WIKI.config, 'logo', {
  83. hasLogo: false,
  84. logoIsSquare: false
  85. })
  86. _.set(WIKI.config, 'mail', {
  87. senderName: '',
  88. senderEmail: '',
  89. host: '',
  90. port: 465,
  91. secure: true,
  92. user: '',
  93. pass: '',
  94. useDKIM: false,
  95. dkimDomainName: '',
  96. dkimKeySelector: '',
  97. dkimPrivateKey: ''
  98. })
  99. _.set(WIKI.config, 'seo', {
  100. description: '',
  101. robots: ['index', 'follow'],
  102. analyticsService: '',
  103. analyticsId: ''
  104. })
  105. _.set(WIKI.config, 'sessionSecret', (await crypto.randomBytesAsync(32)).toString('hex'))
  106. _.set(WIKI.config, 'telemetry', {
  107. isEnabled: req.body.telemetry === true,
  108. clientId: uuid()
  109. })
  110. _.set(WIKI.config, 'theming', {
  111. theme: 'default',
  112. darkMode: false,
  113. iconset: 'mdi',
  114. injectCSS: '',
  115. injectHead: '',
  116. injectBody: ''
  117. })
  118. _.set(WIKI.config, 'title', 'Wiki.js')
  119. // Init Telemetry
  120. WIKI.kernel.initTelemetry()
  121. WIKI.telemetry.sendEvent('setup', 'install-start')
  122. // Basic checks
  123. if (!semver.satisfies(process.version, '>=10.12')) {
  124. throw new Error('Node.js 10.12.x or later required!')
  125. }
  126. // Create directory structure
  127. WIKI.logger.info('Creating data directories...')
  128. const dataPath = path.join(process.cwd(), 'data')
  129. await fs.ensureDir(dataPath)
  130. await fs.emptyDir(path.join(dataPath, 'cache'))
  131. await fs.ensureDir(path.join(dataPath, 'uploads'))
  132. // Generate certificates
  133. WIKI.logger.info('Generating certificates...')
  134. const certs = crypto.generateKeyPairSync('rsa', {
  135. modulusLength: 2048,
  136. publicKeyEncoding: {
  137. type: 'pkcs1',
  138. format: 'pem'
  139. },
  140. privateKeyEncoding: {
  141. type: 'pkcs1',
  142. format: 'pem',
  143. cipher: 'aes-256-cbc',
  144. passphrase: WIKI.config.sessionSecret
  145. }
  146. })
  147. _.set(WIKI.config, 'certs', {
  148. jwk: pem2jwk(certs.publicKey),
  149. public: certs.publicKey,
  150. private: certs.privateKey
  151. })
  152. // Save config to DB
  153. WIKI.logger.info('Persisting config to DB...')
  154. await WIKI.configSvc.saveToDb([
  155. 'auth',
  156. 'certs',
  157. 'company',
  158. 'features',
  159. 'graphEndpoint',
  160. 'host',
  161. 'lang',
  162. 'logo',
  163. 'mail',
  164. 'seo',
  165. 'sessionSecret',
  166. 'telemetry',
  167. 'theming',
  168. 'title'
  169. ])
  170. // Create default locale
  171. WIKI.logger.info('Installing default locale...')
  172. await WIKI.models.locales.query().insert({
  173. code: 'en',
  174. strings: {},
  175. isRTL: false,
  176. name: 'English',
  177. nativeName: 'English'
  178. })
  179. // Create default groups
  180. WIKI.logger.info('Creating default groups...')
  181. const adminGroup = await WIKI.models.groups.query().insert({
  182. id: 1,
  183. name: 'Administrators',
  184. permissions: JSON.stringify(['manage:system']),
  185. pageRules: JSON.stringify([]),
  186. isSystem: true
  187. })
  188. const guestGroup = await WIKI.models.groups.query().insert({
  189. id: 2,
  190. name: 'Guests',
  191. permissions: JSON.stringify(['read:pages', 'read:assets', 'read:comments']),
  192. pageRules: JSON.stringify([
  193. { id: 'guest', roles: ['read:pages', 'read:assets', 'read:comments'], 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. WIKI.telemetry.sendEvent('setup', 'install-loadedmodules')
  211. // Load storage targets
  212. await WIKI.models.storage.refreshTargetsFromDisk()
  213. // Create root administrator
  214. WIKI.logger.info('Creating root administrator...')
  215. await WIKI.models.users.query().delete().where({
  216. providerKey: 'local',
  217. email: req.body.adminEmail
  218. }).orWhere('id', 1)
  219. const adminUser = await WIKI.models.users.query().insert({
  220. id: 1,
  221. email: req.body.adminEmail,
  222. provider: 'local',
  223. password: req.body.adminPassword,
  224. name: 'Administrator',
  225. locale: 'en',
  226. defaultEditor: 'markdown',
  227. tfaIsActive: false,
  228. isActive: true,
  229. isVerified: true
  230. })
  231. await adminUser.$relatedQuery('groups').relate(adminGroup.id)
  232. // Create Guest account
  233. WIKI.logger.info('Creating guest account...')
  234. await WIKI.models.users.query().delete().where({
  235. providerKey: 'local',
  236. email: 'guest@example.com'
  237. }).orWhere('id', 2)
  238. const guestUser = await WIKI.models.users.query().insert({
  239. id: 2,
  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: 'mdi-home',
  261. kind: 'link',
  262. label: 'Home',
  263. target: '/',
  264. targetType: 'home'
  265. }
  266. ]
  267. })
  268. WIKI.logger.info('Setup is complete!')
  269. WIKI.telemetry.sendEvent('setup', 'install-completed')
  270. res.json({
  271. ok: true,
  272. redirectPath: '/',
  273. redirectPort: WIKI.config.port
  274. }).end()
  275. WIKI.config.setup = false
  276. WIKI.logger.info('Stopping Setup...')
  277. WIKI.server.destroy(() => {
  278. WIKI.logger.info('Setup stopped. Starting Wiki.js...')
  279. _.delay(() => {
  280. WIKI.kernel.bootMaster()
  281. }, 1000)
  282. })
  283. } catch (err) {
  284. WIKI.telemetry.sendError(err)
  285. res.json({ ok: false, error: err.message })
  286. }
  287. })
  288. // ----------------------------------------
  289. // Error handling
  290. // ----------------------------------------
  291. app.use(function (req, res, next) {
  292. var err = new Error('Not Found')
  293. err.status = 404
  294. next(err)
  295. })
  296. app.use(function (err, req, res, next) {
  297. res.status(err.status || 500)
  298. res.send({
  299. message: err.message,
  300. error: WIKI.IS_DEBUG ? err : {}
  301. })
  302. WIKI.logger.error(err.message)
  303. WIKI.telemetry.sendError(err)
  304. })
  305. // ----------------------------------------
  306. // Start HTTP server
  307. // ----------------------------------------
  308. WIKI.logger.info(`Starting HTTP server on port ${WIKI.config.port}...`)
  309. app.set('port', WIKI.config.port)
  310. if (WIKI.config.ssl.enabled) {
  311. WIKI.logger.info(`HTTPS Server on port: [ ${WIKI.config.port} ]`)
  312. const tlsOpts = {}
  313. try {
  314. if (WIKI.config.ssl.format === 'pem') {
  315. tlsOpts.key = fs.readFileSync(WIKI.config.ssl.key)
  316. tlsOpts.cert = fs.readFileSync(WIKI.config.ssl.cert)
  317. } else {
  318. tlsOpts.pfx = fs.readFileSync(WIKI.config.ssl.pfx)
  319. }
  320. if (!_.isEmpty(WIKI.config.ssl.passphrase)) {
  321. tlsOpts.passphrase = WIKI.config.ssl.passphrase
  322. }
  323. if (!_.isEmpty(WIKI.config.ssl.dhparam)) {
  324. tlsOpts.dhparam = WIKI.config.ssl.dhparam
  325. }
  326. } catch (err) {
  327. WIKI.logger.error('Failed to setup HTTPS server parameters:')
  328. WIKI.logger.error(err)
  329. return process.exit(1)
  330. }
  331. WIKI.server = https.createServer(tlsOpts, app)
  332. } else {
  333. WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
  334. WIKI.server = http.createServer(app)
  335. }
  336. WIKI.server.listen(WIKI.config.port, WIKI.config.bindIP)
  337. var openConnections = []
  338. WIKI.server.on('connection', (conn) => {
  339. let key = conn.remoteAddress + ':' + conn.remotePort
  340. openConnections[key] = conn
  341. conn.on('close', () => {
  342. openConnections.splice(key, 1)
  343. })
  344. })
  345. WIKI.server.destroy = (cb) => {
  346. WIKI.server.close(cb)
  347. for (let key in openConnections) {
  348. openConnections[key].destroy()
  349. }
  350. }
  351. WIKI.server.on('error', (error) => {
  352. if (error.syscall !== 'listen') {
  353. throw error
  354. }
  355. switch (error.code) {
  356. case 'EACCES':
  357. WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  358. return process.exit(1)
  359. case 'EADDRINUSE':
  360. WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
  361. return process.exit(1)
  362. default:
  363. throw error
  364. }
  365. })
  366. WIKI.server.on('listening', () => {
  367. WIKI.logger.info('HTTP Server: [ RUNNING ]')
  368. WIKI.logger.info('🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻')
  369. WIKI.logger.info('')
  370. WIKI.logger.info(`Browse to http://localhost:${WIKI.config.port}/ to complete setup!`)
  371. WIKI.logger.info('')
  372. WIKI.logger.info('🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺')
  373. })
  374. }