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.

302 lines
8.5 KiB

  1. const autoload = require('auto-load')
  2. const bodyParser = require('body-parser')
  3. const compression = require('compression')
  4. const cookieParser = require('cookie-parser')
  5. const cors = require('cors')
  6. const express = require('express')
  7. const session = require('express-session')
  8. const KnexSessionStore = require('connect-session-knex')(session)
  9. const favicon = require('serve-favicon')
  10. const fs = require('fs-extra')
  11. const http = require('http')
  12. const https = require('https')
  13. const path = require('path')
  14. const _ = require('lodash')
  15. const { ApolloServer } = require('apollo-server-express')
  16. /* global WIKI */
  17. module.exports = async () => {
  18. // ----------------------------------------
  19. // Load core modules
  20. // ----------------------------------------
  21. WIKI.auth = require('./core/auth').init()
  22. WIKI.lang = require('./core/localization').init()
  23. WIKI.mail = require('./core/mail').init()
  24. WIKI.system = require('./core/system').init()
  25. // ----------------------------------------
  26. // Load middlewares
  27. // ----------------------------------------
  28. var mw = autoload(path.join(WIKI.SERVERPATH, '/middlewares'))
  29. var ctrl = autoload(path.join(WIKI.SERVERPATH, '/controllers'))
  30. // ----------------------------------------
  31. // Define Express App
  32. // ----------------------------------------
  33. const app = express()
  34. WIKI.app = app
  35. app.use(compression())
  36. // ----------------------------------------
  37. // Security
  38. // ----------------------------------------
  39. app.use(mw.security)
  40. app.use(cors(WIKI.config.cors))
  41. app.options('*', cors(WIKI.config.cors))
  42. if (WIKI.config.security.securityTrustProxy) {
  43. app.enable('trust proxy')
  44. }
  45. // ----------------------------------------
  46. // Public Assets
  47. // ----------------------------------------
  48. app.use(favicon(path.join(WIKI.ROOTPATH, 'assets', 'favicon.ico')))
  49. app.use(express.static(path.join(WIKI.ROOTPATH, 'assets'), {
  50. index: false,
  51. maxAge: '7d'
  52. }))
  53. // ----------------------------------------
  54. // Passport Authentication
  55. // ----------------------------------------
  56. app.use(cookieParser())
  57. app.use(session({
  58. secret: WIKI.config.sessionSecret,
  59. resave: false,
  60. saveUninitialized: false,
  61. store: new KnexSessionStore({
  62. knex: WIKI.models.knex
  63. })
  64. }))
  65. app.use(WIKI.auth.passport.initialize())
  66. app.use(WIKI.auth.authenticate)
  67. // ----------------------------------------
  68. // SEO
  69. // ----------------------------------------
  70. app.use(mw.seo)
  71. // ----------------------------------------
  72. // View Engine Setup
  73. // ----------------------------------------
  74. app.set('views', path.join(WIKI.SERVERPATH, 'views'))
  75. app.set('view engine', 'pug')
  76. app.use(bodyParser.json({ limit: '1mb' }))
  77. app.use(bodyParser.urlencoded({ extended: false, limit: '1mb' }))
  78. // ----------------------------------------
  79. // Localization
  80. // ----------------------------------------
  81. WIKI.lang.attachMiddleware(app)
  82. // ----------------------------------------
  83. // View accessible data
  84. // ----------------------------------------
  85. app.locals.analyticsCode = {}
  86. app.locals.basedir = WIKI.ROOTPATH
  87. app.locals.config = WIKI.config
  88. app.locals.pageMeta = {
  89. title: '',
  90. description: WIKI.config.description,
  91. image: '',
  92. url: '/'
  93. }
  94. app.locals.devMode = WIKI.devMode
  95. // ----------------------------------------
  96. // HMR (Dev Mode Only)
  97. // ----------------------------------------
  98. if (global.DEV) {
  99. app.use(global.WP_DEV.devMiddleware)
  100. app.use(global.WP_DEV.hotMiddleware)
  101. }
  102. // ----------------------------------------
  103. // Apollo Server (GraphQL)
  104. // ----------------------------------------
  105. const graphqlSchema = require('./graph')
  106. const apolloServer = new ApolloServer({
  107. ...graphqlSchema,
  108. context: ({ req, res }) => ({ req, res }),
  109. subscriptions: {
  110. onConnect: (connectionParams, webSocket) => {
  111. },
  112. path: '/graphql-subscriptions'
  113. }
  114. })
  115. apolloServer.applyMiddleware({ app })
  116. // ----------------------------------------
  117. // Routing
  118. // ----------------------------------------
  119. app.use(async (req, res, next) => {
  120. res.locals.siteConfig = {
  121. title: WIKI.config.title,
  122. theme: WIKI.config.theming.theme,
  123. darkMode: WIKI.config.theming.darkMode,
  124. lang: WIKI.config.lang.code,
  125. rtl: WIKI.config.lang.rtl,
  126. company: WIKI.config.company,
  127. logoUrl: WIKI.config.logoUrl
  128. }
  129. res.locals.langs = await WIKI.models.locales.getNavLocales({ cache: true })
  130. res.locals.analyticsCode = await WIKI.models.analytics.getCode({ cache: true })
  131. next()
  132. })
  133. app.use('/', ctrl.auth)
  134. app.use('/', ctrl.upload)
  135. app.use('/', ctrl.common)
  136. // ----------------------------------------
  137. // Error handling
  138. // ----------------------------------------
  139. app.use((req, res, next) => {
  140. var err = new Error('Not Found')
  141. err.status = 404
  142. next(err)
  143. })
  144. app.use((err, req, res, next) => {
  145. res.status(err.status || 500)
  146. _.set(res.locals, 'pageMeta.title', 'Error')
  147. res.render('error', {
  148. message: err.message,
  149. error: WIKI.IS_DEBUG ? err : {}
  150. })
  151. })
  152. // ----------------------------------------
  153. // HTTP/S server
  154. // ----------------------------------------
  155. let srvConnections = {}
  156. app.set('port', WIKI.config.port)
  157. if (WIKI.config.ssl.enabled) {
  158. WIKI.logger.info(`HTTPS Server on port: [ ${WIKI.config.port} ]`)
  159. const tlsOpts = {}
  160. try {
  161. if (WIKI.config.ssl.format === 'pem') {
  162. tlsOpts.key = fs.readFileSync(WIKI.config.ssl.key)
  163. tlsOpts.cert = fs.readFileSync(WIKI.config.ssl.cert)
  164. } else {
  165. tlsOpts.pfx = fs.readFileSync(WIKI.config.ssl.pfx)
  166. }
  167. if (!_.isEmpty(WIKI.config.ssl.passphrase)) {
  168. tlsOpts.passphrase = WIKI.config.ssl.passphrase
  169. }
  170. if (!_.isEmpty(WIKI.config.ssl.dhparam)) {
  171. tlsOpts.dhparam = WIKI.config.ssl.dhparam
  172. }
  173. } catch (err) {
  174. WIKI.logger.error('Failed to setup HTTPS server parameters:')
  175. WIKI.logger.error(err)
  176. return process.exit(1)
  177. }
  178. WIKI.server = https.createServer(tlsOpts, app)
  179. // HTTP Redirect Server
  180. if (WIKI.config.ssl.redirectNonSSLPort) {
  181. WIKI.serverAlt = http.createServer((req, res) => {
  182. res.writeHead(301, { 'Location': 'https://' + req.headers['host'] + req.url })
  183. res.end()
  184. })
  185. }
  186. } else {
  187. WIKI.logger.info(`HTTP Server on port: [ ${WIKI.config.port} ]`)
  188. WIKI.server = http.createServer(app)
  189. }
  190. apolloServer.installSubscriptionHandlers(WIKI.server)
  191. WIKI.server.listen(WIKI.config.port, WIKI.config.bindIP)
  192. WIKI.server.on('error', (error) => {
  193. if (error.syscall !== 'listen') {
  194. throw error
  195. }
  196. // handle specific listen errors with friendly messages
  197. switch (error.code) {
  198. case 'EACCES':
  199. WIKI.logger.error('Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  200. return process.exit(1)
  201. case 'EADDRINUSE':
  202. WIKI.logger.error('Port ' + WIKI.config.port + ' is already in use!')
  203. return process.exit(1)
  204. default:
  205. throw error
  206. }
  207. })
  208. WIKI.server.on('connection', conn => {
  209. let key = `${conn.remoteAddress}:${conn.remotePort}`
  210. srvConnections[key] = conn
  211. conn.on('close', function() {
  212. delete srvConnections[key]
  213. })
  214. })
  215. WIKI.server.on('listening', () => {
  216. if (WIKI.config.ssl.enabled) {
  217. WIKI.logger.info('HTTPS Server: [ RUNNING ]')
  218. // Start HTTP Redirect Server
  219. if (WIKI.config.ssl.redirectNonSSLPort) {
  220. WIKI.serverAlt.listen(WIKI.config.ssl.redirectNonSSLPort, WIKI.config.bindIP)
  221. WIKI.serverAlt.on('error', (error) => {
  222. if (error.syscall !== 'listen') {
  223. throw error
  224. }
  225. switch (error.code) {
  226. case 'EACCES':
  227. WIKI.logger.error('(HTTP Redirect) Listening on port ' + WIKI.config.port + ' requires elevated privileges!')
  228. return process.exit(1)
  229. case 'EADDRINUSE':
  230. WIKI.logger.error('(HTTP Redirect) Port ' + WIKI.config.port + ' is already in use!')
  231. return process.exit(1)
  232. default:
  233. throw error
  234. }
  235. })
  236. WIKI.serverAlt.on('listening', () => {
  237. WIKI.logger.info('HTTP Server: [ RUNNING in redirect mode ]')
  238. })
  239. }
  240. } else {
  241. WIKI.logger.info('HTTP Server: [ RUNNING ]')
  242. }
  243. })
  244. WIKI.server.destroy = (cb) => {
  245. WIKI.server.close(cb)
  246. for (let key in srvConnections) {
  247. srvConnections[key].destroy()
  248. }
  249. if (WIKI.config.ssl.enabled && WIKI.config.ssl.redirectNonSSLPort) {
  250. WIKI.serverAlt.close(cb)
  251. }
  252. }
  253. return true
  254. }