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.

439 lines
13 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 { v4: uuid } = require('uuid')
  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 Promise = require('bluebird')
  9. const fs = require('fs-extra')
  10. const _ = require('lodash')
  11. const crypto = Promise.promisifyAll(require('crypto'))
  12. const pem2jwk = require('pem-jwk').pem2jwk
  13. const semver = require('semver')
  14. /* global WIKI */
  15. module.exports = () => {
  16. WIKI.config.site = {
  17. path: '',
  18. title: 'Wiki.js'
  19. }
  20. WIKI.system = require('./core/system')
  21. // ----------------------------------------
  22. // Define Express App
  23. // ----------------------------------------
  24. let app = express()
  25. app.use(compression())
  26. // ----------------------------------------
  27. // Public Assets
  28. // ----------------------------------------
  29. app.use(favicon(path.join(WIKI.ROOTPATH, 'assets', 'favicon.ico')))
  30. app.use(express.static(path.join(WIKI.ROOTPATH, 'assets')))
  31. // ----------------------------------------
  32. // View Engine Setup
  33. // ----------------------------------------
  34. app.set('views', path.join(WIKI.SERVERPATH, 'views'))
  35. app.set('view engine', 'pug')
  36. app.use(bodyParser.json())
  37. app.use(bodyParser.urlencoded({ extended: false }))
  38. app.locals.config = WIKI.config
  39. app.locals.data = WIKI.data
  40. app.locals._ = require('lodash')
  41. app.locals.devMode = WIKI.devMode
  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. ], false)
  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. locale: 'en',
  282. items: [
  283. {
  284. id: uuid(),
  285. icon: 'mdi-home',
  286. kind: 'link',
  287. label: 'Home',
  288. target: '/',
  289. targetType: 'home',
  290. visibilityMode: 'all',
  291. visibilityGroups: null
  292. }
  293. ]
  294. }
  295. ]
  296. })
  297. WIKI.logger.info('Setup is complete!')
  298. // WIKI.telemetry.sendEvent('setup', 'install-completed')
  299. res.json({
  300. ok: true,
  301. redirectPath: '/',
  302. redirectPort: WIKI.config.port
  303. }).end()
  304. if (WIKI.config.telemetry.isEnabled) {
  305. await WIKI.telemetry.sendInstanceEvent('INSTALL')
  306. }
  307. WIKI.config.setup = false
  308. WIKI.logger.info('Stopping Setup...')
  309. WIKI.server.destroy(() => {
  310. WIKI.logger.info('Setup stopped. Starting Wiki.js...')
  311. _.delay(() => {
  312. WIKI.kernel.bootMaster()
  313. }, 1000)
  314. })
  315. } catch (err) {
  316. try {
  317. await WIKI.models.knex('settings').truncate()
  318. } catch (err) {}
  319. WIKI.telemetry.sendError(err)
  320. res.json({ ok: false, error: err.message })
  321. }
  322. })
  323. // ----------------------------------------
  324. // Error handling
  325. // ----------------------------------------
  326. app.use(function (req, res, next) {
  327. var err = new Error('Not Found')
  328. err.status = 404
  329. next(err)
  330. })
  331. app.use(function (err, req, res, next) {
  332. res.status(err.status || 500)
  333. res.send({
  334. message: err.message,
  335. error: WIKI.IS_DEBUG ? err : {}
  336. })
  337. WIKI.logger.error(err.message)
  338. WIKI.telemetry.sendError(err)
  339. })
  340. // ----------------------------------------
  341. // Start HTTP server
  342. // ----------------------------------------
  343. WIKI.logger.info(`Starting HTTP server on port ${WIKI.config.port}...`)
  344. app.set('port', WIKI.config.port)
  345. WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
  346. WIKI.server = http.createServer(app)
  347. WIKI.server.listen(WIKI.config.port, WIKI.config.bindIP)
  348. var openConnections = []
  349. WIKI.server.on('connection', (conn) => {
  350. let key = conn.remoteAddress + ':' + conn.remotePort
  351. openConnections[key] = conn
  352. conn.on('close', () => {
  353. openConnections.splice(key, 1)
  354. })
  355. })
  356. WIKI.server.destroy = (cb) => {
  357. WIKI.server.close(cb)
  358. for (let key in openConnections) {
  359. openConnections[key].destroy()
  360. }
  361. }
  362. WIKI.server.on('error', (error) => {
  363. if (error.syscall !== 'listen') {
  364. throw error
  365. }
  366. switch (error.code) {
  367. case 'EACCES':
  368. WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  369. return process.exit(1)
  370. case 'EADDRINUSE':
  371. WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
  372. return process.exit(1)
  373. default:
  374. throw error
  375. }
  376. })
  377. WIKI.server.on('listening', () => {
  378. WIKI.logger.info('HTTP Server: [ RUNNING ]')
  379. WIKI.logger.info('🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻')
  380. WIKI.logger.info('')
  381. WIKI.logger.info(`Browse to http://localhost:${WIKI.config.port}/ to complete setup!`)
  382. WIKI.logger.info('')
  383. WIKI.logger.info('🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺')
  384. })
  385. }