server.ts 6.8 KB

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