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.

452 lines
14 KiB

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