forked from requarks/wiki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetup.js
451 lines (397 loc) · 13.5 KB
/
setup.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
const path = require('path')
const { v4: uuid } = require('uuid')
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')
/* global WIKI */
module.exports = () => {
WIKI.config.site = {
path: '',
title: 'Wiki.js'
}
WIKI.system = require('./core/system')
// ----------------------------------------
// Define Express App
// ----------------------------------------
let app = express()
app.use(compression())
// ----------------------------------------
// Public Assets
// ----------------------------------------
app.use(favicon(path.join(WIKI.ROOTPATH, 'assets', 'favicon.ico')))
app.use('/_assets', express.static(path.join(WIKI.ROOTPATH, 'assets')))
// ----------------------------------------
// View Engine Setup
// ----------------------------------------
app.set('views', path.join(WIKI.SERVERPATH, 'views'))
app.set('view engine', 'pug')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.locals.config = WIKI.config
app.locals.data = WIKI.data
app.locals._ = require('lodash')
app.locals.devMode = WIKI.devMode
// ----------------------------------------
// HMR (Dev Mode Only)
// ----------------------------------------
if (global.DEV) {
app.use(global.WP_DEV.devMiddleware)
app.use(global.WP_DEV.hotMiddleware)
}
// ----------------------------------------
// Controllers
// ----------------------------------------
app.get('*', async (req, res) => {
let packageObj = await fs.readJson(path.join(WIKI.ROOTPATH, 'package.json'))
res.render('setup', { packageObj })
})
/**
* Finalize
*/
app.post('/finalize', async (req, res) => {
try {
// Set config
_.set(WIKI.config, 'auth', {
audience: 'urn:wiki.js',
tokenExpiration: '30m',
tokenRenewal: '14d'
})
_.set(WIKI.config, 'company', '')
_.set(WIKI.config, 'features', {
featurePageRatings: true,
featurePageComments: true,
featurePersonalWikis: true
})
_.set(WIKI.config, 'graphEndpoint', 'https://graph.requarks.io')
_.set(WIKI.config, 'host', req.body.siteUrl)
_.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,
name: '',
secure: true,
verifySSL: true,
user: '',
pass: '',
useDKIM: false,
dkimDomainName: '',
dkimKeySelector: '',
dkimPrivateKey: ''
})
_.set(WIKI.config, 'seo', {
description: '',
robots: ['index', 'follow'],
analyticsService: '',
analyticsId: ''
})
_.set(WIKI.config, 'sessionSecret', (await crypto.randomBytesAsync(32)).toString('hex'))
_.set(WIKI.config, 'telemetry', {
isEnabled: req.body.telemetry === true,
clientId: uuid()
})
_.set(WIKI.config, 'theming', {
theme: 'default',
darkMode: false,
iconset: 'mdi',
injectCSS: '',
injectHead: '',
injectBody: ''
})
_.set(WIKI.config, 'title', 'Wiki.js')
// Init Telemetry
WIKI.kernel.initTelemetry()
// WIKI.telemetry.sendEvent('setup', 'install-start')
// Basic checks
if (!semver.satisfies(process.version, '>=10.12')) {
throw new Error('Node.js 10.12.x or later required!')
}
// Create directory structure
WIKI.logger.info('Creating data directories...')
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'))
// 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
}
})
_.set(WIKI.config, 'certs', {
jwk: pem2jwk(certs.publicKey),
public: certs.publicKey,
private: certs.privateKey
})
// Save config to DB
WIKI.logger.info('Persisting config to DB...')
await WIKI.configSvc.saveToDb([
'auth',
'certs',
'company',
'features',
'graphEndpoint',
'host',
'lang',
'logo',
'mail',
'seo',
'sessionSecret',
'telemetry',
'theming',
'uploads',
'title'
], false)
// Truncate tables (reset from previous failed install)
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()
await WIKI.models.knex.raw('ALTER TABLE `groups` AUTO_INCREMENT = 1')
await WIKI.models.knex.raw('ALTER TABLE `users` AUTO_INCREMENT = 1')
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
}
// Create default locale
WIKI.logger.info('Installing default locale...')
await WIKI.models.locales.query().insert({
code: 'en',
strings: {},
isRTL: false,
name: 'English',
nativeName: 'English'
})
// Create default groups
WIKI.logger.info('Creating default groups...')
const adminGroup = await WIKI.models.groups.query().insert({
name: 'Administrators',
permissions: JSON.stringify(['manage:system']),
pageRules: JSON.stringify([]),
isSystem: true
})
const guestGroup = await WIKI.models.groups.query().insert({
name: 'Guests',
permissions: JSON.stringify(['read:pages', 'read:assets', 'read:comments']),
pageRules: JSON.stringify([
{ id: 'guest', roles: ['read:pages', 'read:assets', 'read:comments'], match: 'START', deny: false, path: '', locales: [] }
]),
isSystem: true
})
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.')
}
// Load local authentication strategy
await WIKI.models.authentication.query().insert({
key: 'local',
config: {},
selfRegistration: false,
isEnabled: true,
domainWhitelist: {v: []},
autoEnrollGroups: {v: []},
order: 0,
strategyKey: 'local',
displayName: 'Local'
})
// Load editors + enable default
await WIKI.models.editors.refreshEditorsFromDisk()
await WIKI.models.editors.query().patch({ isEnabled: true }).where('key', 'markdown')
// Load loggers
await WIKI.models.loggers.refreshLoggersFromDisk()
// Load renderers
await WIKI.models.renderers.refreshRenderersFromDisk()
// Load search engines + enable default
await WIKI.models.searchEngines.refreshSearchEnginesFromDisk()
await WIKI.models.searchEngines.query().patch({ isEnabled: true }).where('key', 'db')
// WIKI.telemetry.sendEvent('setup', 'install-loadedmodules')
// Load storage targets
await WIKI.models.storage.refreshTargetsFromDisk()
// Create root administrator
WIKI.logger.info('Creating root administrator...')
const adminUser = await WIKI.models.users.query().insert({
email: req.body.adminEmail.toLowerCase(),
provider: 'local',
password: req.body.adminPassword,
name: 'Administrator',
locale: 'en',
defaultEditor: 'markdown',
tfaIsActive: false,
isActive: true,
isVerified: true
})
await adminUser.$relatedQuery('groups').relate(adminGroup.id)
// Create Guest account
WIKI.logger.info('Creating guest account...')
const guestUser = await WIKI.models.users.query().insert({
provider: 'local',
email: '[email protected]',
name: 'Guest',
password: '',
locale: 'en',
defaultEditor: 'markdown',
tfaIsActive: false,
isSystem: true,
isActive: true,
isVerified: true
})
await guestUser.$relatedQuery('groups').relate(guestGroup.id)
if (adminUser.id !== 1 || guestUser.id !== 2) {
throw new Error('Incorrect users auto-increment configuration! Should start at 0 and increment by 1. Contact your database administrator.')
}
// Create site nav
WIKI.logger.info('Creating default site navigation')
await WIKI.models.navigation.query().insert({
key: 'site',
config: [
{
locale: 'en',
items: [
{
id: uuid(),
icon: 'mdi-home',
kind: 'link',
label: 'Home',
target: '/',
targetType: 'home',
visibilityMode: 'all',
visibilityGroups: null
}
]
}
]
})
WIKI.logger.info('Setup is complete!')
// WIKI.telemetry.sendEvent('setup', 'install-completed')
res.json({
ok: true,
redirectPath: '/',
redirectPort: WIKI.config.port
}).end()
if (WIKI.config.telemetry.isEnabled) {
await WIKI.telemetry.sendInstanceEvent('INSTALL')
}
WIKI.config.setup = false
WIKI.logger.info('Stopping Setup...')
WIKI.server.destroy(() => {
WIKI.logger.info('Setup stopped. Starting Wiki.js...')
_.delay(() => {
WIKI.kernel.bootMaster()
}, 1000)
})
} catch (err) {
try {
await WIKI.models.knex('settings').truncate()
} catch (err) {}
WIKI.telemetry.sendError(err)
res.json({ ok: false, error: err.message })
}
})
// ----------------------------------------
// Error handling
// ----------------------------------------
app.use(function (req, res, next) {
const 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,
error: WIKI.IS_DEBUG ? err : {}
})
WIKI.logger.error(err.message)
WIKI.telemetry.sendError(err)
})
// ----------------------------------------
// Start HTTP server
// ----------------------------------------
WIKI.logger.info(`Starting HTTP server on port ${WIKI.config.port}...`)
app.set('port', WIKI.config.port)
WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
WIKI.server = http.createServer(app)
WIKI.server.listen(WIKI.config.port, WIKI.config.bindIP)
var openConnections = []
WIKI.server.on('connection', (conn) => {
let key = conn.remoteAddress + ':' + conn.remotePort
openConnections[key] = conn
conn.on('close', () => {
openConnections.splice(key, 1)
})
})
WIKI.server.destroy = (cb) => {
WIKI.server.close(cb)
for (let key in openConnections) {
openConnections[key].destroy()
}
}
WIKI.server.on('error', (error) => {
if (error.syscall !== 'listen') {
throw error
}
switch (error.code) {
case 'EACCES':
WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
return process.exit(1)
case 'EADDRINUSE':
WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
return process.exit(1)
default:
throw error
}
})
WIKI.server.on('listening', () => {
WIKI.logger.info('HTTP Server: [ RUNNING ]')
WIKI.logger.info('🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻🔻')
WIKI.logger.info('')
WIKI.logger.info(`Browse to http://YOUR-SERVER-IP:${WIKI.config.port}/ to complete setup!`)
WIKI.logger.info('')
WIKI.logger.info('🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺🔺')
})
}