server.ts 6.7 KB

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