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.

441 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('/_assets', 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. verifySSL: 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. await fs.ensureDir(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath))
  129. await fs.emptyDir(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, 'cache'))
  130. await fs.ensureDir(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, 'uploads'))
  131. // Generate certificates
  132. WIKI.logger.info('Generating certificates...')
  133. const certs = crypto.generateKeyPairSync('rsa', {
  134. modulusLength: 2048,
  135. publicKeyEncoding: {
  136. type: 'pkcs1',
  137. format: 'pem'
  138. },
  139. privateKeyEncoding: {
  140. type: 'pkcs1',
  141. format: 'pem',
  142. cipher: 'aes-256-cbc',
  143. passphrase: WIKI.config.sessionSecret
  144. }
  145. })
  146. _.set(WIKI.config, 'certs', {
  147. jwk: pem2jwk(certs.publicKey),
  148. public: certs.publicKey,
  149. private: certs.privateKey
  150. })
  151. // Save config to DB
  152. WIKI.logger.info('Persisting config to DB...')
  153. await WIKI.configSvc.saveToDb([
  154. 'auth',
  155. 'certs',
  156. 'company',
  157. 'features',
  158. 'graphEndpoint',
  159. 'host',
  160. 'lang',
  161. 'logo',
  162. 'mail',
  163. 'seo',
  164. 'sessionSecret',
  165. 'telemetry',
  166. 'theming',
  167. 'uploads',
  168. 'title'
  169. ], false)
  170. // Truncate tables (reset from previous failed install)
  171. await WIKI.models.locales.query().where('code', '!=', 'x').del()
  172. await WIKI.models.navigation.query().truncate()
  173. switch (WIKI.config.db.type) {
  174. case 'postgres':
  175. await WIKI.models.knex.raw('TRUNCATE groups, users CASCADE')
  176. break
  177. case 'mysql':
  178. case 'mariadb':
  179. await WIKI.models.groups.query().where('id', '>', 0).del()
  180. await WIKI.models.users.query().where('id', '>', 0).del()
  181. await WIKI.models.knex.raw('ALTER TABLE `groups` AUTO_INCREMENT = 1')
  182. await WIKI.models.knex.raw('ALTER TABLE `users` AUTO_INCREMENT = 1')
  183. break
  184. case 'mssql':
  185. await WIKI.models.groups.query().del()
  186. await WIKI.models.users.query().del()
  187. await WIKI.models.knex.raw(`
  188. IF EXISTS (SELECT * FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = 'groups' AND last_value IS NOT NULL)
  189. DBCC CHECKIDENT ([groups], RESEED, 0)
  190. `)
  191. await WIKI.models.knex.raw(`
  192. IF EXISTS (SELECT * FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = 'users' AND last_value IS NOT NULL)
  193. DBCC CHECKIDENT ([users], RESEED, 0)
  194. `)
  195. break
  196. case 'sqlite':
  197. await WIKI.models.groups.query().truncate()
  198. await WIKI.models.users.query().truncate()
  199. break
  200. }
  201. // Create default locale
  202. WIKI.logger.info('Installing default locale...')
  203. await WIKI.models.locales.query().insert({
  204. code: 'en',
  205. strings: {},
  206. isRTL: false,
  207. name: 'English',
  208. nativeName: 'English'
  209. })
  210. // Create default groups
  211. WIKI.logger.info('Creating default groups...')
  212. const adminGroup = await WIKI.models.groups.query().insert({
  213. name: 'Administrators',
  214. permissions: JSON.stringify(['manage:system']),
  215. pageRules: JSON.stringify([]),
  216. isSystem: true
  217. })
  218. const guestGroup = await WIKI.models.groups.query().insert({
  219. name: 'Guests',
  220. permissions: JSON.stringify(['read:pages', 'read:assets', 'read:comments']),
  221. pageRules: JSON.stringify([
  222. { id: 'guest', roles: ['read:pages', 'read:assets', 'read:comments'], match: 'START', deny: false, path: '', locales: [] }
  223. ]),
  224. isSystem: true
  225. })
  226. if (adminGroup.id !== 1 || guestGroup.id !== 2) {
  227. throw new Error('Incorrect groups auto-increment configuration! Should start at 0 and increment by 1. Contact your database administrator.')
  228. }
  229. // Load authentication strategies + enable local
  230. await WIKI.models.authentication.refreshStrategiesFromDisk()
  231. await WIKI.models.authentication.query().patch({ isEnabled: true }).where('key', 'local')
  232. // Load editors + enable default
  233. await WIKI.models.editors.refreshEditorsFromDisk()
  234. await WIKI.models.editors.query().patch({ isEnabled: true }).where('key', 'markdown')
  235. // Load loggers
  236. await WIKI.models.loggers.refreshLoggersFromDisk()
  237. // Load renderers
  238. await WIKI.models.renderers.refreshRenderersFromDisk()
  239. // Load search engines + enable default
  240. await WIKI.models.searchEngines.refreshSearchEnginesFromDisk()
  241. await WIKI.models.searchEngines.query().patch({ isEnabled: true }).where('key', 'db')
  242. // WIKI.telemetry.sendEvent('setup', 'install-loadedmodules')
  243. // Load storage targets
  244. await WIKI.models.storage.refreshTargetsFromDisk()
  245. // Create root administrator
  246. WIKI.logger.info('Creating root administrator...')
  247. const adminUser = await WIKI.models.users.query().insert({
  248. email: req.body.adminEmail,
  249. provider: 'local',
  250. password: req.body.adminPassword,
  251. name: 'Administrator',
  252. locale: 'en',
  253. defaultEditor: 'markdown',
  254. tfaIsActive: false,
  255. isActive: true,
  256. isVerified: true
  257. })
  258. await adminUser.$relatedQuery('groups').relate(adminGroup.id)
  259. // Create Guest account
  260. WIKI.logger.info('Creating guest account...')
  261. const guestUser = await WIKI.models.users.query().insert({
  262. provider: 'local',
  263. email: 'guest@example.com',
  264. name: 'Guest',
  265. password: '',
  266. locale: 'en',
  267. defaultEditor: 'markdown',
  268. tfaIsActive: false,
  269. isSystem: true,
  270. isActive: true,
  271. isVerified: true
  272. })
  273. await guestUser.$relatedQuery('groups').relate(guestGroup.id)
  274. if (adminUser.id !== 1 || guestUser.id !== 2) {
  275. throw new Error('Incorrect users auto-increment configuration! Should start at 0 and increment by 1. Contact your database administrator.')
  276. }
  277. // Create site nav
  278. WIKI.logger.info('Creating default site navigation')
  279. await WIKI.models.navigation.query().insert({
  280. key: 'site',
  281. config: [
  282. {
  283. locale: 'en',
  284. items: [
  285. {
  286. id: uuid(),
  287. icon: 'mdi-home',
  288. kind: 'link',
  289. label: 'Home',
  290. target: '/',
  291. targetType: 'home',
  292. visibilityMode: 'all',
  293. visibilityGroups: null
  294. }
  295. ]
  296. }
  297. ]
  298. })
  299. WIKI.logger.info('Setup is complete!')
  300. // WIKI.telemetry.sendEvent('setup', 'install-completed')
  301. res.json({
  302. ok: true,
  303. redirectPath: '/',
  304. redirectPort: WIKI.config.port
  305. }).end()
  306. if (WIKI.config.telemetry.isEnabled) {
  307. await WIKI.telemetry.sendInstanceEvent('INSTALL')
  308. }
  309. WIKI.config.setup = false
  310. WIKI.logger.info('Stopping Setup...')
  311. WIKI.server.destroy(() => {
  312. WIKI.logger.info('Setup stopped. Starting Wiki.js...')
  313. _.delay(() => {
  314. WIKI.kernel.bootMaster()
  315. }, 1000)
  316. })
  317. } catch (err) {
  318. try {
  319. await WIKI.models.knex('settings').truncate()
  320. } catch (err) {}
  321. WIKI.telemetry.sendError(err)
  322. res.json({ ok: false, error: err.message })
  323. }
  324. })
  325. // ----------------------------------------
  326. // Error handling
  327. // ----------------------------------------
  328. app.use(function (req, res, next) {
  329. var err = new Error('Not Found')
  330. err.status = 404
  331. next(err)
  332. })
  333. app.use(function (err, req, res, next) {
  334. res.status(err.status || 500)
  335. res.send({
  336. message: err.message,
  337. error: WIKI.IS_DEBUG ? err : {}
  338. })
  339. WIKI.logger.error(err.message)
  340. WIKI.telemetry.sendError(err)
  341. })
  342. // ----------------------------------------
  343. // Start HTTP server
  344. // ----------------------------------------
  345. WIKI.logger.info(`Starting HTTP server on port ${WIKI.config.port}...`)
  346. app.set('port', WIKI.config.port)
  347. WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
  348. WIKI.server = http.createServer(app)
  349. WIKI.server.listen(WIKI.config.port, WIKI.config.bindIP)
  350. var openConnections = []
  351. WIKI.server.on('connection', (conn) => {
  352. let key = conn.remoteAddress + ':' + conn.remotePort
  353. openConnections[key] = conn
  354. conn.on('close', () => {
  355. openConnections.splice(key, 1)
  356. })
  357. })
  358. WIKI.server.destroy = (cb) => {
  359. WIKI.server.close(cb)
  360. for (let key in openConnections) {
  361. openConnections[key].destroy()
  362. }
  363. }
  364. WIKI.server.on('error', (error) => {
  365. if (error.syscall !== 'listen') {
  366. throw error
  367. }
  368. switch (error.code) {
  369. case 'EACCES':
  370. WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  371. return process.exit(1)
  372. case 'EADDRINUSE':
  373. WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
  374. return process.exit(1)
  375. default:
  376. throw error
  377. }
  378. })
  379. WIKI.server.on('listening', () => {
  380. WIKI.logger.info('HTTP Server: [ RUNNING ]')
  381. WIKI.logger.info('🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻')
  382. WIKI.logger.info('')
  383. WIKI.logger.info(`Browse to http://localhost:${WIKI.config.port}/ to complete setup!`)
  384. WIKI.logger.info('')
  385. WIKI.logger.info('🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺')
  386. })
  387. }