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.

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