setup.js 13.8 KB
Newer Older
1
const path = require('path')
2
const uuid = require('uuid/v4')
3 4 5 6 7 8 9 10 11 12 13 14
const bodyParser = require('body-parser')
const compression = require('compression')
const express = require('express')
const favicon = require('serve-favicon')
const http = require('http')
const https = require('https')
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')
15

16
/* global WIKI */
17

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

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

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

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

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

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

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

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

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

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

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

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

64 65 66 67
  // ----------------------------------------
  // Controllers
  // ----------------------------------------

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

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

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

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

      // Create directory structure
      WIKI.logger.info('Creating data directories...')
147 148 149
      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
150

151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
      // 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
        }
      })

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

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

192
      // Truncate tables (reset from previous failed install)
193 194 195 196 197 198 199 200 201 202
      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()
203 204
          await WIKI.models.knex.raw('ALTER TABLE `groups` AUTO_INCREMENT = 1')
          await WIKI.models.knex.raw('ALTER TABLE `users` AUTO_INCREMENT = 1')
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
          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
222 223
      }

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

234
      // Create default groups
235 236 237 238 239

      WIKI.logger.info('Creating default groups...')
      const adminGroup = await WIKI.models.groups.query().insert({
        name: 'Administrators',
        permissions: JSON.stringify(['manage:system']),
240
        pageRules: JSON.stringify([]),
241 242 243 244
        isSystem: true
      })
      const guestGroup = await WIKI.models.groups.query().insert({
        name: 'Guests',
245
        permissions: JSON.stringify(['read:pages', 'read:assets', 'read:comments']),
246
        pageRules: JSON.stringify([
247
          { id: 'guest', roles: ['read:pages', 'read:assets', 'read:comments'], match: 'START', deny: false, path: '', locales: [] }
248
        ]),
249 250
        isSystem: true
      })
251 252 253
      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.')
      }
254

255
      // Load authentication strategies + enable local
256 257
      await WIKI.models.authentication.refreshStrategiesFromDisk()
      await WIKI.models.authentication.query().patch({ isEnabled: true }).where('key', 'local')
258 259

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

263 264 265
      // Load loggers
      await WIKI.models.loggers.refreshLoggersFromDisk()

266 267 268
      // Load renderers
      await WIKI.models.renderers.refreshRenderersFromDisk()

269 270 271 272
      // Load search engines + enable default
      await WIKI.models.searchEngines.refreshSearchEnginesFromDisk()
      await WIKI.models.searchEngines.query().patch({ isEnabled: true }).where('key', 'db')

Nick's avatar
Nick committed
273 274
      WIKI.telemetry.sendEvent('setup', 'install-loadedmodules')

275
      // Load storage targets
276
      await WIKI.models.storage.refreshTargetsFromDisk()
277

NGPixel's avatar
NGPixel committed
278
      // Create root administrator
279
      WIKI.logger.info('Creating root administrator...')
280
      const adminUser = await WIKI.models.users.query().insert({
NGPixel's avatar
NGPixel committed
281 282
        email: req.body.adminEmail,
        provider: 'local',
283
        password: req.body.adminPassword,
NGPixel's avatar
NGPixel committed
284
        name: 'Administrator',
285
        locale: 'en',
286
        defaultEditor: 'markdown',
287 288 289
        tfaIsActive: false,
        isActive: true,
        isVerified: true
NGPixel's avatar
NGPixel committed
290
      })
291
      await adminUser.$relatedQuery('groups').relate(adminGroup.id)
NGPixel's avatar
NGPixel committed
292

293
      // Create Guest account
294
      WIKI.logger.info('Creating guest account...')
295 296 297 298 299 300 301
      const guestUser = await WIKI.models.users.query().insert({
        provider: 'local',
        email: 'guest@example.com',
        name: 'Guest',
        password: '',
        locale: 'en',
        defaultEditor: 'markdown',
302
        tfaIsActive: false,
303 304 305
        isSystem: true,
        isActive: true,
        isVerified: true
306 307
      })
      await guestUser.$relatedQuery('groups').relate(guestGroup.id)
308
      if (adminUser.id !== 1 || guestUser.id !== 2) {
309
        throw new Error('Incorrect users auto-increment configuration! Should start at 0 and increment by 1. Contact your database administrator.')
310
      }
311

312 313 314 315 316
      // 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
317
        config: [
318
          {
319
            id: uuid(),
Nick's avatar
Nick committed
320
            icon: 'mdi-home',
321 322 323 324 325
            kind: 'link',
            label: 'Home',
            target: '/',
            targetType: 'home'
          }
Nicolas Giard's avatar
Nicolas Giard committed
326
        ]
327 328
      })

329
      WIKI.logger.info('Setup is complete!')
Nick's avatar
Nick committed
330
      WIKI.telemetry.sendEvent('setup', 'install-completed')
331 332
      res.json({
        ok: true,
333
        redirectPath: '/',
334
        redirectPort: WIKI.config.port
335 336
      }).end()

337 338
      WIKI.config.setup = false

339
      WIKI.logger.info('Stopping Setup...')
340
      WIKI.server.destroy(() => {
341
        WIKI.logger.info('Setup stopped. Starting Wiki.js...')
342
        _.delay(() => {
343
          WIKI.kernel.bootMaster()
344 345
        }, 1000)
      })
346
    } catch (err) {
347 348 349
      try {
        await WIKI.models.knex('settings').truncate()
      } catch (err) {}
Nick's avatar
Nick committed
350
      WIKI.telemetry.sendError(err)
351
      res.json({ ok: false, error: err.message })
352
    }
NGPixel's avatar
NGPixel committed
353 354
  })

355 356 357 358 359 360 361 362 363 364 365 366 367 368
  // ----------------------------------------
  // Error handling
  // ----------------------------------------

  app.use(function (req, res, next) {
    var err = new Error('Not Found')
    err.status = 404
    next(err)
  })

  app.use(function (err, req, res, next) {
    res.status(err.status || 500)
    res.send({
      message: err.message,
369
      error: WIKI.IS_DEBUG ? err : {}
370
    })
371 372
    WIKI.logger.error(err.message)
    WIKI.telemetry.sendError(err)
373 374 375 376 377 378
  })

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

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

381
  app.set('port', WIKI.config.port)
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408

  if (WIKI.config.ssl.enabled) {
    WIKI.logger.info(`HTTPS Server on port: [ ${WIKI.config.port} ]`)
    const tlsOpts = {}
    try {
      if (WIKI.config.ssl.format === 'pem') {
        tlsOpts.key = fs.readFileSync(WIKI.config.ssl.key)
        tlsOpts.cert = fs.readFileSync(WIKI.config.ssl.cert)
      } else {
        tlsOpts.pfx = fs.readFileSync(WIKI.config.ssl.pfx)
      }
      if (!_.isEmpty(WIKI.config.ssl.passphrase)) {
        tlsOpts.passphrase = WIKI.config.ssl.passphrase
      }
      if (!_.isEmpty(WIKI.config.ssl.dhparam)) {
        tlsOpts.dhparam = WIKI.config.ssl.dhparam
      }
    } catch (err) {
      WIKI.logger.error('Failed to setup HTTPS server parameters:')
      WIKI.logger.error(err)
      return process.exit(1)
    }
    WIKI.server = https.createServer(tlsOpts, app)
  } else {
    WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
    WIKI.server = http.createServer(app)
  }
409
  WIKI.server.listen(WIKI.config.port, WIKI.config.bindIP)
410 411 412

  var openConnections = []

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

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

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

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

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