setup.js 13.5 KB
Newer Older
1
const path = require('path')
2
const { v4: uuid } = require('uuid')
3 4 5 6 7 8 9 10 11 12 13
const bodyParser = require('body-parser')
const compression = require('compression')
const express = require('express')
const favicon = require('serve-favicon')
const http = require('http')
const Promise = require('bluebird')
const fs = require('fs-extra')
const _ = require('lodash')
const crypto = Promise.promisifyAll(require('crypto'))
const pem2jwk = require('pem-jwk').pem2jwk
const semver = require('semver')
14

15
/* global WIKI */
16

17
module.exports = () => {
18
  WIKI.config.site = {
19
    path: '',
20
    title: 'Wiki.js'
21 22
  }

23
  WIKI.system = require('./core/system')
24

25 26 27 28
  // ----------------------------------------
  // Define Express App
  // ----------------------------------------

29
  let app = express()
30 31 32 33 34 35
  app.use(compression())

  // ----------------------------------------
  // Public Assets
  // ----------------------------------------

36
  app.use(favicon(path.join(WIKI.ROOTPATH, 'assets', 'favicon.ico')))
37
  app.use('/_assets', express.static(path.join(WIKI.ROOTPATH, 'assets')))
38 39 40 41 42

  // ----------------------------------------
  // View Engine Setup
  // ----------------------------------------

43
  app.set('views', path.join(WIKI.SERVERPATH, 'views'))
44 45 46 47 48
  app.set('view engine', 'pug')

  app.use(bodyParser.json())
  app.use(bodyParser.urlencoded({ extended: false }))

49 50
  app.locals.config = WIKI.config
  app.locals.data = WIKI.data
51
  app.locals._ = require('lodash')
52
  app.locals.devMode = WIKI.devMode
53

NGPixel's avatar
NGPixel committed
54 55 56 57 58
  // ----------------------------------------
  // HMR (Dev Mode Only)
  // ----------------------------------------

  if (global.DEV) {
59 60
    app.use(global.WP_DEV.devMiddleware)
    app.use(global.WP_DEV.hotMiddleware)
NGPixel's avatar
NGPixel committed
61 62
  }

63 64 65 66
  // ----------------------------------------
  // Controllers
  // ----------------------------------------

67
  app.get('*', async (req, res) => {
68
    let packageObj = await fs.readJson(path.join(WIKI.ROOTPATH, 'package.json'))
Nick's avatar
Nick committed
69
    res.render('setup', { packageObj })
70 71
  })

NGPixel's avatar
NGPixel committed
72
  /**
73
   * Finalize
NGPixel's avatar
NGPixel committed
74
   */
75 76
  app.post('/finalize', async (req, res) => {
    try {
77
      // Set config
78 79 80 81 82
      _.set(WIKI.config, 'auth', {
        audience: 'urn:wiki.js',
        tokenExpiration: '30m',
        tokenRenewal: '14d'
      })
83 84 85 86 87 88
      _.set(WIKI.config, 'company', '')
      _.set(WIKI.config, 'features', {
        featurePageRatings: true,
        featurePageComments: true,
        featurePersonalWikis: true
      })
89
      _.set(WIKI.config, 'graphEndpoint', 'https://graph.requarks.io')
90
      _.set(WIKI.config, 'host', req.body.siteUrl)
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
      _.set(WIKI.config, 'lang', {
        code: 'en',
        autoUpdate: true,
        namespacing: false,
        namespaces: []
      })
      _.set(WIKI.config, 'logo', {
        hasLogo: false,
        logoIsSquare: false
      })
      _.set(WIKI.config, 'mail', {
        senderName: '',
        senderEmail: '',
        host: '',
        port: 465,
106
        name: '',
107
        secure: true,
108
        verifySSL: true,
109 110 111 112 113 114 115 116 117 118
        user: '',
        pass: '',
        useDKIM: false,
        dkimDomainName: '',
        dkimKeySelector: '',
        dkimPrivateKey: ''
      })
      _.set(WIKI.config, 'seo', {
        description: '',
        robots: ['index', 'follow'],
119 120
        analyticsService: '',
        analyticsId: ''
121
      })
122
      _.set(WIKI.config, 'sessionSecret', (await crypto.randomBytesAsync(32)).toString('hex'))
123
      _.set(WIKI.config, 'telemetry', {
124
        isEnabled: req.body.telemetry === true,
Nick's avatar
Nick committed
125
        clientId: uuid()
126 127 128
      })
      _.set(WIKI.config, 'theming', {
        theme: 'default',
129 130 131 132 133
        darkMode: false,
        iconset: 'mdi',
        injectCSS: '',
        injectHead: '',
        injectBody: ''
134
      })
135
      _.set(WIKI.config, 'title', 'Wiki.js')
136

Nick's avatar
Nick committed
137 138
      // Init Telemetry
      WIKI.kernel.initTelemetry()
139
      // WIKI.telemetry.sendEvent('setup', 'install-start')
Nick's avatar
Nick committed
140 141

      // Basic checks
142 143
      if (!semver.satisfies(process.version, '>=10.12')) {
        throw new Error('Node.js 10.12.x or later required!')
Nick's avatar
Nick committed
144 145 146 147
      }

      // Create directory structure
      WIKI.logger.info('Creating data directories...')
148 149 150
      await fs.ensureDir(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath))
      await fs.emptyDir(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, 'cache'))
      await fs.ensureDir(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, 'uploads'))
Nick's avatar
Nick committed
151

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
      // Generate certificates
      WIKI.logger.info('Generating certificates...')
      const certs = crypto.generateKeyPairSync('rsa', {
        modulusLength: 2048,
        publicKeyEncoding: {
          type: 'pkcs1',
          format: 'pem'
        },
        privateKeyEncoding: {
          type: 'pkcs1',
          format: 'pem',
          cipher: 'aes-256-cbc',
          passphrase: WIKI.config.sessionSecret
        }
      })

168 169 170 171 172
      _.set(WIKI.config, 'certs', {
        jwk: pem2jwk(certs.publicKey),
        public: certs.publicKey,
        private: certs.privateKey
      })
173

NGPixel's avatar
NGPixel committed
174
      // Save config to DB
175
      WIKI.logger.info('Persisting config to DB...')
176
      await WIKI.configSvc.saveToDb([
177
        'auth',
178 179 180
        'certs',
        'company',
        'features',
181
        'graphEndpoint',
182
        'host',
183
        'lang',
184 185 186
        'logo',
        'mail',
        'seo',
187 188
        'sessionSecret',
        'telemetry',
189
        'theming',
190
        'uploads',
191
        'title'
192
      ], false)
NGPixel's avatar
NGPixel committed
193

194
      // Truncate tables (reset from previous failed install)
195 196 197 198 199 200 201 202 203 204
      await WIKI.models.locales.query().where('code', '!=', 'x').del()
      await WIKI.models.navigation.query().truncate()
      switch (WIKI.config.db.type) {
        case 'postgres':
          await WIKI.models.knex.raw('TRUNCATE groups, users CASCADE')
          break
        case 'mysql':
        case 'mariadb':
          await WIKI.models.groups.query().where('id', '>', 0).del()
          await WIKI.models.users.query().where('id', '>', 0).del()
205 206
          await WIKI.models.knex.raw('ALTER TABLE `groups` AUTO_INCREMENT = 1')
          await WIKI.models.knex.raw('ALTER TABLE `users` AUTO_INCREMENT = 1')
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
          break
        case 'mssql':
          await WIKI.models.groups.query().del()
          await WIKI.models.users.query().del()
          await WIKI.models.knex.raw(`
            IF EXISTS (SELECT * FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = 'groups' AND last_value IS NOT NULL)
              DBCC CHECKIDENT ([groups], RESEED, 0)
          `)
          await WIKI.models.knex.raw(`
            IF EXISTS (SELECT * FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = 'users' AND last_value IS NOT NULL)
              DBCC CHECKIDENT ([users], RESEED, 0)
          `)
          break
        case 'sqlite':
          await WIKI.models.groups.query().truncate()
          await WIKI.models.users.query().truncate()
          break
224 225
      }

226 227
      // Create default locale
      WIKI.logger.info('Installing default locale...')
228
      await WIKI.models.locales.query().insert({
229
        code: 'en',
230
        strings: {},
231 232 233 234 235
        isRTL: false,
        name: 'English',
        nativeName: 'English'
      })

236
      // Create default groups
237 238 239 240 241

      WIKI.logger.info('Creating default groups...')
      const adminGroup = await WIKI.models.groups.query().insert({
        name: 'Administrators',
        permissions: JSON.stringify(['manage:system']),
242
        pageRules: JSON.stringify([]),
243 244 245 246
        isSystem: true
      })
      const guestGroup = await WIKI.models.groups.query().insert({
        name: 'Guests',
247
        permissions: JSON.stringify(['read:pages', 'read:assets', 'read:comments']),
248
        pageRules: JSON.stringify([
249
          { id: 'guest', roles: ['read:pages', 'read:assets', 'read:comments'], match: 'START', deny: false, path: '', locales: [] }
250
        ]),
251 252
        isSystem: true
      })
253 254 255
      if (adminGroup.id !== 1 || guestGroup.id !== 2) {
        throw new Error('Incorrect groups auto-increment configuration! Should start at 0 and increment by 1. Contact your database administrator.')
      }
256

257 258 259 260 261
      // Load local authentication strategy
      await WIKI.models.authentication.query().insert({
        key: 'local',
        config: {},
        selfRegistration: false,
262
        isEnabled: true,
263 264 265 266 267 268
        domainWhitelist: {v: []},
        autoEnrollGroups: {v: []},
        order: 0,
        strategyKey: 'local',
        displayName: 'Local'
      })
269 270

      // Load editors + enable default
271 272
      await WIKI.models.editors.refreshEditorsFromDisk()
      await WIKI.models.editors.query().patch({ isEnabled: true }).where('key', 'markdown')
273

274 275 276
      // Load loggers
      await WIKI.models.loggers.refreshLoggersFromDisk()

277 278 279
      // Load renderers
      await WIKI.models.renderers.refreshRenderersFromDisk()

280 281 282 283
      // Load search engines + enable default
      await WIKI.models.searchEngines.refreshSearchEnginesFromDisk()
      await WIKI.models.searchEngines.query().patch({ isEnabled: true }).where('key', 'db')

284
      // WIKI.telemetry.sendEvent('setup', 'install-loadedmodules')
Nick's avatar
Nick committed
285

286
      // Load storage targets
287
      await WIKI.models.storage.refreshTargetsFromDisk()
288

NGPixel's avatar
NGPixel committed
289
      // Create root administrator
290
      WIKI.logger.info('Creating root administrator...')
291
      const adminUser = await WIKI.models.users.query().insert({
292
        email: req.body.adminEmail.toLowerCase(),
NGPixel's avatar
NGPixel committed
293
        provider: 'local',
294
        password: req.body.adminPassword,
NGPixel's avatar
NGPixel committed
295
        name: 'Administrator',
296
        locale: 'en',
297
        defaultEditor: 'markdown',
298 299 300
        tfaIsActive: false,
        isActive: true,
        isVerified: true
NGPixel's avatar
NGPixel committed
301
      })
302
      await adminUser.$relatedQuery('groups').relate(adminGroup.id)
NGPixel's avatar
NGPixel committed
303

304
      // Create Guest account
305
      WIKI.logger.info('Creating guest account...')
306 307 308 309 310 311 312
      const guestUser = await WIKI.models.users.query().insert({
        provider: 'local',
        email: 'guest@example.com',
        name: 'Guest',
        password: '',
        locale: 'en',
        defaultEditor: 'markdown',
313
        tfaIsActive: false,
314 315 316
        isSystem: true,
        isActive: true,
        isVerified: true
317 318
      })
      await guestUser.$relatedQuery('groups').relate(guestGroup.id)
319
      if (adminUser.id !== 1 || guestUser.id !== 2) {
320
        throw new Error('Incorrect users auto-increment configuration! Should start at 0 and increment by 1. Contact your database administrator.')
321
      }
322

323 324 325 326 327
      // Create site nav

      WIKI.logger.info('Creating default site navigation')
      await WIKI.models.navigation.query().insert({
        key: 'site',
Nicolas Giard's avatar
Nicolas Giard committed
328
        config: [
329
          {
330 331 332 333 334 335 336 337
            locale: 'en',
            items: [
              {
                id: uuid(),
                icon: 'mdi-home',
                kind: 'link',
                label: 'Home',
                target: '/',
338 339 340
                targetType: 'home',
                visibilityMode: 'all',
                visibilityGroups: null
341 342
              }
            ]
343
          }
Nicolas Giard's avatar
Nicolas Giard committed
344
        ]
345 346
      })

347
      WIKI.logger.info('Setup is complete!')
348
      // WIKI.telemetry.sendEvent('setup', 'install-completed')
349 350
      res.json({
        ok: true,
351
        redirectPath: '/',
352
        redirectPort: WIKI.config.port
353 354
      }).end()

355 356 357 358
      if (WIKI.config.telemetry.isEnabled) {
        await WIKI.telemetry.sendInstanceEvent('INSTALL')
      }

359 360
      WIKI.config.setup = false

361
      WIKI.logger.info('Stopping Setup...')
362
      WIKI.server.destroy(() => {
363
        WIKI.logger.info('Setup stopped. Starting Wiki.js...')
364
        _.delay(() => {
365
          WIKI.kernel.bootMaster()
366 367
        }, 1000)
      })
368
    } catch (err) {
369 370 371
      try {
        await WIKI.models.knex('settings').truncate()
      } catch (err) {}
Nick's avatar
Nick committed
372
      WIKI.telemetry.sendError(err)
373
      res.json({ ok: false, error: err.message })
374
    }
NGPixel's avatar
NGPixel committed
375 376
  })

377 378 379 380 381
  // ----------------------------------------
  // Error handling
  // ----------------------------------------

  app.use(function (req, res, next) {
382
    const err = new Error('Not Found')
383 384 385 386 387 388 389 390
    err.status = 404
    next(err)
  })

  app.use(function (err, req, res, next) {
    res.status(err.status || 500)
    res.send({
      message: err.message,
391
      error: WIKI.IS_DEBUG ? err : {}
392
    })
393 394
    WIKI.logger.error(err.message)
    WIKI.telemetry.sendError(err)
395 396 397 398 399 400
  })

  // ----------------------------------------
  // Start HTTP server
  // ----------------------------------------

Nick's avatar
Nick committed
401
  WIKI.logger.info(`Starting HTTP server on port ${WIKI.config.port}...`)
402

403
  app.set('port', WIKI.config.port)
404

405 406
  WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
  WIKI.server = http.createServer(app)
407
  WIKI.server.listen(WIKI.config.port, WIKI.config.bindIP)
408 409 410

  var openConnections = []

411
  WIKI.server.on('connection', (conn) => {
412 413 414
    let key = conn.remoteAddress + ':' + conn.remotePort
    openConnections[key] = conn
    conn.on('close', () => {
Nick's avatar
Nick committed
415
      openConnections.splice(key, 1)
416 417 418
    })
  })

419 420
  WIKI.server.destroy = (cb) => {
    WIKI.server.close(cb)
421 422 423 424 425
    for (let key in openConnections) {
      openConnections[key].destroy()
    }
  }

426
  WIKI.server.on('error', (error) => {
427 428 429 430 431 432
    if (error.syscall !== 'listen') {
      throw error
    }

    switch (error.code) {
      case 'EACCES':
433
        WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
NGPixel's avatar
NGPixel committed
434
        return process.exit(1)
435
      case 'EADDRINUSE':
436
        WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
NGPixel's avatar
NGPixel committed
437
        return process.exit(1)
438 439 440 441 442
      default:
        throw error
    }
  })

443
  WIKI.server.on('listening', () => {
444
    WIKI.logger.info('HTTP Server: [ RUNNING ]')
445 446
    WIKI.logger.info('🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻')
    WIKI.logger.info('')
447
    WIKI.logger.info(`Browse to http://YOUR-SERVER-IP:${WIKI.config.port}/ to complete setup!`)
448 449
    WIKI.logger.info('')
    WIKI.logger.info('🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺')
450 451
  })
}