server.ts 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. // FIXME: https://github.com/nodejs/node/pull/16853
  2. require('tls').DEFAULT_ECDH_CURVE = 'auto'
  3. import { isTestInstance } from './server/helpers/core-utils'
  4. if (isTestInstance()) {
  5. require('source-map-support').install()
  6. }
  7. // ----------- Node modules -----------
  8. import * as bodyParser from 'body-parser'
  9. import * as express from 'express'
  10. import * as morgan from 'morgan'
  11. import * as cors from 'cors'
  12. import * as cookieParser from 'cookie-parser'
  13. import * as helmet from 'helmet'
  14. import * as useragent from 'useragent'
  15. import * as anonymize from 'ip-anonymize'
  16. process.title = 'peertube'
  17. // Create our main app
  18. const app = express()
  19. // ----------- Core checker -----------
  20. import { checkMissedConfig, checkFFmpeg } from './server/initializers/checker-before-init'
  21. // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
  22. import { logger } from './server/helpers/logger'
  23. import { API_VERSION, CONFIG, CACHE } from './server/initializers/constants'
  24. const missed = checkMissedConfig()
  25. if (missed.length !== 0) {
  26. logger.error('Your configuration files miss keys: ' + missed)
  27. process.exit(-1)
  28. }
  29. checkFFmpeg(CONFIG)
  30. .catch(err => {
  31. logger.error('Error in ffmpeg check.', { err })
  32. process.exit(-1)
  33. })
  34. import { checkConfig, checkActivityPubUrls } from './server/initializers/checker-after-init'
  35. const errorMessage = checkConfig()
  36. if (errorMessage !== null) {
  37. throw new Error(errorMessage)
  38. }
  39. // Trust our proxy (IP forwarding...)
  40. app.set('trust proxy', CONFIG.TRUST_PROXY)
  41. // Security middleware
  42. app.use(helmet({
  43. frameguard: {
  44. action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
  45. },
  46. hsts: false
  47. }))
  48. // ----------- Database -----------
  49. // Initialize database and models
  50. import { initDatabaseModels } from './server/initializers/database'
  51. import { migrate } from './server/initializers/migrator'
  52. migrate()
  53. .then(() => initDatabaseModels(false))
  54. .then(() => startApplication())
  55. .catch(err => {
  56. logger.error('Cannot start application.', { err })
  57. process.exit(-1)
  58. })
  59. // ----------- PeerTube modules -----------
  60. import { installApplication } from './server/initializers'
  61. import { Emailer } from './server/lib/emailer'
  62. import { JobQueue } from './server/lib/job-queue'
  63. import { VideosPreviewCache, VideosCaptionCache } from './server/lib/cache'
  64. import {
  65. activityPubRouter,
  66. apiRouter,
  67. clientsRouter,
  68. feedsRouter,
  69. staticRouter,
  70. servicesRouter,
  71. webfingerRouter,
  72. trackerRouter,
  73. createWebsocketServer
  74. } from './server/controllers'
  75. import { advertiseDoNotTrack } from './server/middlewares/dnt'
  76. import { Redis } from './server/lib/redis'
  77. import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
  78. import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
  79. import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
  80. import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
  81. import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
  82. // ----------- Command line -----------
  83. // ----------- App -----------
  84. // Enable CORS for develop
  85. if (isTestInstance()) {
  86. app.use(cors({
  87. origin: '*',
  88. exposedHeaders: 'Retry-After',
  89. credentials: true
  90. }))
  91. }
  92. // For the logger
  93. morgan.token('remote-addr', req => {
  94. return (req.get('DNT') === '1') ?
  95. anonymize(req.ip || (req.connection && req.connection.remoteAddress) || undefined,
  96. 16, // bitmask for IPv4
  97. 16 // bitmask for IPv6
  98. ) :
  99. req.ip
  100. })
  101. morgan.token('user-agent', req => (req.get('DNT') === '1') ?
  102. useragent.parse(req.get('user-agent')).family : req.get('user-agent'))
  103. app.use(morgan('combined', {
  104. stream: { write: logger.info.bind(logger) }
  105. }))
  106. // For body requests
  107. app.use(bodyParser.urlencoded({ extended: false }))
  108. app.use(bodyParser.json({
  109. type: [ 'application/json', 'application/*+json' ],
  110. limit: '500kb'
  111. }))
  112. // Cookies
  113. app.use(cookieParser())
  114. // W3C DNT Tracking Status
  115. app.use(advertiseDoNotTrack)
  116. // ----------- Views, routes and static files -----------
  117. // API
  118. const apiRoute = '/api/' + API_VERSION
  119. app.use(apiRoute, apiRouter)
  120. // Services (oembed...)
  121. app.use('/services', servicesRouter)
  122. app.use('/', activityPubRouter)
  123. app.use('/', feedsRouter)
  124. app.use('/', webfingerRouter)
  125. app.use('/', trackerRouter)
  126. // Static files
  127. app.use('/', staticRouter)
  128. // Client files, last valid routes!
  129. app.use('/', clientsRouter)
  130. // ----------- Errors -----------
  131. // Catch 404 and forward to error handler
  132. app.use(function (req, res, next) {
  133. const err = new Error('Not Found')
  134. err['status'] = 404
  135. next(err)
  136. })
  137. app.use(function (err, req, res, next) {
  138. let error = 'Unknown error.'
  139. if (err) {
  140. error = err.stack || err.message || err
  141. }
  142. // Sequelize error
  143. const sql = err.parent ? err.parent.sql : undefined
  144. logger.error('Error in controller.', { err: error, sql })
  145. return res.status(err.status || 500).end()
  146. })
  147. const server = createWebsocketServer(app)
  148. // ----------- Run -----------
  149. async function startApplication () {
  150. const port = CONFIG.LISTEN.PORT
  151. const hostname = CONFIG.LISTEN.HOSTNAME
  152. await installApplication()
  153. // Check activity pub urls are valid
  154. checkActivityPubUrls()
  155. .catch(err => {
  156. logger.error('Error in ActivityPub URLs checker.', { err })
  157. process.exit(-1)
  158. })
  159. // Email initialization
  160. Emailer.Instance.init()
  161. await Emailer.Instance.checkConnectionOrDie()
  162. await JobQueue.Instance.init()
  163. // Caches initializations
  164. VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, CACHE.PREVIEWS.MAX_AGE)
  165. VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, CACHE.VIDEO_CAPTIONS.MAX_AGE)
  166. // Enable Schedulers
  167. BadActorFollowScheduler.Instance.enable()
  168. RemoveOldJobsScheduler.Instance.enable()
  169. UpdateVideosScheduler.Instance.enable()
  170. YoutubeDlUpdateScheduler.Instance.enable()
  171. VideosRedundancyScheduler.Instance.enable()
  172. // Redis initialization
  173. Redis.Instance.init()
  174. // Make server listening
  175. server.listen(port, hostname, () => {
  176. logger.info('Server listening on %s:%d', hostname, port)
  177. logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
  178. })
  179. process.on('exit', () => {
  180. JobQueue.Instance.terminate()
  181. })
  182. process.on('SIGINT', () => process.exit(0))
  183. }