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.

449 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 { 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 local authentication strategy
  230. await WIKI.models.authentication.query().insert({
  231. key: 'local',
  232. config: {},
  233. selfRegistration: false,
  234. domainWhitelist: {v: []},
  235. autoEnrollGroups: {v: []},
  236. order: 0,
  237. strategyKey: 'local',
  238. displayName: 'Local'
  239. })
  240. // Load editors + enable default
  241. await WIKI.models.editors.refreshEditorsFromDisk()
  242. await WIKI.models.editors.query().patch({ isEnabled: true }).where('key', 'markdown')
  243. // Load loggers
  244. await WIKI.models.loggers.refreshLoggersFromDisk()
  245. // Load renderers
  246. await WIKI.models.renderers.refreshRenderersFromDisk()
  247. // Load search engines + enable default
  248. await WIKI.models.searchEngines.refreshSearchEnginesFromDisk()
  249. await WIKI.models.searchEngines.query().patch({ isEnabled: true }).where('key', 'db')
  250. // WIKI.telemetry.sendEvent('setup', 'install-loadedmodules')
  251. // Load storage targets
  252. await WIKI.models.storage.refreshTargetsFromDisk()
  253. // Create root administrator
  254. WIKI.logger.info('Creating root administrator...')
  255. const adminUser = await WIKI.models.users.query().insert({
  256. email: req.body.adminEmail,
  257. provider: 'local',
  258. password: req.body.adminPassword,
  259. name: 'Administrator',
  260. locale: 'en',
  261. defaultEditor: 'markdown',
  262. tfaIsActive: false,
  263. isActive: true,
  264. isVerified: true
  265. })
  266. await adminUser.$relatedQuery('groups').relate(adminGroup.id)
  267. // Create Guest account
  268. WIKI.logger.info('Creating guest account...')
  269. const guestUser = await WIKI.models.users.query().insert({
  270. provider: 'local',
  271. email: 'guest@example.com',
  272. name: 'Guest',
  273. password: '',
  274. locale: 'en',
  275. defaultEditor: 'markdown',
  276. tfaIsActive: false,
  277. isSystem: true,
  278. isActive: true,
  279. isVerified: true
  280. })
  281. await guestUser.$relatedQuery('groups').relate(guestGroup.id)
  282. if (adminUser.id !== 1 || guestUser.id !== 2) {
  283. throw new Error('Incorrect users auto-increment configuration! Should start at 0 and increment by 1. Contact your database administrator.')
  284. }
  285. // Create site nav
  286. WIKI.logger.info('Creating default site navigation')
  287. await WIKI.models.navigation.query().insert({
  288. key: 'site',
  289. config: [
  290. {
  291. locale: 'en',
  292. items: [
  293. {
  294. id: uuid(),
  295. icon: 'mdi-home',
  296. kind: 'link',
  297. label: 'Home',
  298. target: '/',
  299. targetType: 'home',
  300. visibilityMode: 'all',
  301. visibilityGroups: null
  302. }
  303. ]
  304. }
  305. ]
  306. })
  307. WIKI.logger.info('Setup is complete!')
  308. // WIKI.telemetry.sendEvent('setup', 'install-completed')
  309. res.json({
  310. ok: true,
  311. redirectPath: '/',
  312. redirectPort: WIKI.config.port
  313. }).end()
  314. if (WIKI.config.telemetry.isEnabled) {
  315. await WIKI.telemetry.sendInstanceEvent('INSTALL')
  316. }
  317. WIKI.config.setup = false
  318. WIKI.logger.info('Stopping Setup...')
  319. WIKI.server.destroy(() => {
  320. WIKI.logger.info('Setup stopped. Starting Wiki.js...')
  321. _.delay(() => {
  322. WIKI.kernel.bootMaster()
  323. }, 1000)
  324. })
  325. } catch (err) {
  326. try {
  327. await WIKI.models.knex('settings').truncate()
  328. } catch (err) {}
  329. WIKI.telemetry.sendError(err)
  330. res.json({ ok: false, error: err.message })
  331. }
  332. })
  333. // ----------------------------------------
  334. // Error handling
  335. // ----------------------------------------
  336. app.use(function (req, res, next) {
  337. var err = new Error('Not Found')
  338. err.status = 404
  339. next(err)
  340. })
  341. app.use(function (err, req, res, next) {
  342. res.status(err.status || 500)
  343. res.send({
  344. message: err.message,
  345. error: WIKI.IS_DEBUG ? err : {}
  346. })
  347. WIKI.logger.error(err.message)
  348. WIKI.telemetry.sendError(err)
  349. })
  350. // ----------------------------------------
  351. // Start HTTP server
  352. // ----------------------------------------
  353. WIKI.logger.info(`Starting HTTP server on port ${WIKI.config.port}...`)
  354. app.set('port', WIKI.config.port)
  355. WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
  356. WIKI.server = http.createServer(app)
  357. WIKI.server.listen(WIKI.config.port, WIKI.config.bindIP)
  358. var openConnections = []
  359. WIKI.server.on('connection', (conn) => {
  360. let key = conn.remoteAddress + ':' + conn.remotePort
  361. openConnections[key] = conn
  362. conn.on('close', () => {
  363. openConnections.splice(key, 1)
  364. })
  365. })
  366. WIKI.server.destroy = (cb) => {
  367. WIKI.server.close(cb)
  368. for (let key in openConnections) {
  369. openConnections[key].destroy()
  370. }
  371. }
  372. WIKI.server.on('error', (error) => {
  373. if (error.syscall !== 'listen') {
  374. throw error
  375. }
  376. switch (error.code) {
  377. case 'EACCES':
  378. WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  379. return process.exit(1)
  380. case 'EADDRINUSE':
  381. WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
  382. return process.exit(1)
  383. default:
  384. throw error
  385. }
  386. })
  387. WIKI.server.on('listening', () => {
  388. WIKI.logger.info('HTTP Server: [ RUNNING ]')
  389. WIKI.logger.info('🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻')
  390. WIKI.logger.info('')
  391. WIKI.logger.info(`Browse to http://localhost:${WIKI.config.port}/ to complete setup!`)
  392. WIKI.logger.info('')
  393. WIKI.logger.info('🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺')
  394. })
  395. }