setup.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. ])
  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. }
  291. ]
  292. }
  293. ]
  294. })
  295. WIKI.logger.info('Setup is complete!')
  296. // WIKI.telemetry.sendEvent('setup', 'install-completed')
  297. res.json({
  298. ok: true,
  299. redirectPath: '/',
  300. redirectPort: WIKI.config.port
  301. }).end()
  302. if (WIKI.config.telemetry.isEnabled) {
  303. await WIKI.telemetry.sendInstanceEvent('INSTALL')
  304. }
  305. WIKI.config.setup = false
  306. WIKI.logger.info('Stopping Setup...')
  307. WIKI.server.destroy(() => {
  308. WIKI.logger.info('Setup stopped. Starting Wiki.js...')
  309. _.delay(() => {
  310. WIKI.kernel.bootMaster()
  311. }, 1000)
  312. })
  313. } catch (err) {
  314. try {
  315. await WIKI.models.knex('settings').truncate()
  316. } catch (err) {}
  317. WIKI.telemetry.sendError(err)
  318. res.json({ ok: false, error: err.message })
  319. }
  320. })
  321. // ----------------------------------------
  322. // Error handling
  323. // ----------------------------------------
  324. app.use(function (req, res, next) {
  325. var err = new Error('Not Found')
  326. err.status = 404
  327. next(err)
  328. })
  329. app.use(function (err, req, res, next) {
  330. res.status(err.status || 500)
  331. res.send({
  332. message: err.message,
  333. error: WIKI.IS_DEBUG ? err : {}
  334. })
  335. WIKI.logger.error(err.message)
  336. WIKI.telemetry.sendError(err)
  337. })
  338. // ----------------------------------------
  339. // Start HTTP server
  340. // ----------------------------------------
  341. WIKI.logger.info(`Starting HTTP server on port ${WIKI.config.port}...`)
  342. app.set('port', WIKI.config.port)
  343. WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
  344. WIKI.server = http.createServer(app)
  345. WIKI.server.listen(WIKI.config.port, WIKI.config.bindIP)
  346. var openConnections = []
  347. WIKI.server.on('connection', (conn) => {
  348. let key = conn.remoteAddress + ':' + conn.remotePort
  349. openConnections[key] = conn
  350. conn.on('close', () => {
  351. openConnections.splice(key, 1)
  352. })
  353. })
  354. WIKI.server.destroy = (cb) => {
  355. WIKI.server.close(cb)
  356. for (let key in openConnections) {
  357. openConnections[key].destroy()
  358. }
  359. }
  360. WIKI.server.on('error', (error) => {
  361. if (error.syscall !== 'listen') {
  362. throw error
  363. }
  364. switch (error.code) {
  365. case 'EACCES':
  366. WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  367. return process.exit(1)
  368. case 'EADDRINUSE':
  369. WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
  370. return process.exit(1)
  371. default:
  372. throw error
  373. }
  374. })
  375. WIKI.server.on('listening', () => {
  376. WIKI.logger.info('HTTP Server: [ RUNNING ]')
  377. WIKI.logger.info('🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻')
  378. WIKI.logger.info('')
  379. WIKI.logger.info(`Browse to http://localhost:${WIKI.config.port}/ to complete setup!`)
  380. WIKI.logger.info('')
  381. WIKI.logger.info('🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺')
  382. })
  383. }