server.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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 } 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. createWebsocketTrackerServer, botsRouter
  77. } from './server/controllers'
  78. import { advertiseDoNotTrack } from './server/middlewares/dnt'
  79. import { Redis } from './server/lib/redis'
  80. import { ActorFollowScheduler } from './server/lib/schedulers/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. import { PeerTubeSocket } from './server/lib/peertube-socket'
  87. // ----------- Command line -----------
  88. cli
  89. .option('--no-client', 'Start PeerTube without client interface')
  90. .parse(process.argv)
  91. // ----------- App -----------
  92. // Enable CORS for develop
  93. if (isTestInstance()) {
  94. app.use(cors({
  95. origin: '*',
  96. exposedHeaders: 'Retry-After',
  97. credentials: true
  98. }))
  99. }
  100. // For the logger
  101. morgan.token('remote-addr', req => {
  102. return (req.get('DNT') === '1') ?
  103. anonymize(req.ip || (req.connection && req.connection.remoteAddress) || undefined,
  104. 16, // bitmask for IPv4
  105. 16 // bitmask for IPv6
  106. ) :
  107. req.ip
  108. })
  109. morgan.token('user-agent', req => (req.get('DNT') === '1') ?
  110. useragent.parse(req.get('user-agent')).family : req.get('user-agent'))
  111. app.use(morgan('combined', {
  112. stream: { write: logger.info.bind(logger) }
  113. }))
  114. // For body requests
  115. app.use(bodyParser.urlencoded({ extended: false }))
  116. app.use(bodyParser.json({
  117. type: [ 'application/json', 'application/*+json' ],
  118. limit: '500kb',
  119. verify: (req: express.Request, _, buf: Buffer) => {
  120. const valid = isHTTPSignatureDigestValid(buf, req)
  121. if (valid !== true) throw new Error('Invalid digest')
  122. }
  123. }))
  124. // Cookies
  125. app.use(cookieParser())
  126. // W3C DNT Tracking Status
  127. app.use(advertiseDoNotTrack)
  128. // ----------- Views, routes and static files -----------
  129. // API
  130. const apiRoute = '/api/' + API_VERSION
  131. app.use(apiRoute, apiRouter)
  132. // Services (oembed...)
  133. app.use('/services', servicesRouter)
  134. app.use('/', activityPubRouter)
  135. app.use('/', feedsRouter)
  136. app.use('/', webfingerRouter)
  137. app.use('/', trackerRouter)
  138. app.use('/', botsRouter)
  139. // Static files
  140. app.use('/', staticRouter)
  141. // Client files, last valid routes!
  142. if (cli.client) app.use('/', clientsRouter)
  143. // ----------- Errors -----------
  144. // Catch 404 and forward to error handler
  145. app.use(function (req, res, next) {
  146. const err = new Error('Not Found')
  147. err['status'] = 404
  148. next(err)
  149. })
  150. app.use(function (err, req, res, next) {
  151. let error = 'Unknown error.'
  152. if (err) {
  153. error = err.stack || err.message || err
  154. }
  155. // Sequelize error
  156. const sql = err.parent ? err.parent.sql : undefined
  157. logger.error('Error in controller.', { err: error, sql })
  158. return res.status(err.status || 500).end()
  159. })
  160. const server = createWebsocketTrackerServer(app)
  161. // ----------- Run -----------
  162. async function startApplication () {
  163. const port = CONFIG.LISTEN.PORT
  164. const hostname = CONFIG.LISTEN.HOSTNAME
  165. await installApplication()
  166. // Check activity pub urls are valid
  167. checkActivityPubUrls()
  168. .catch(err => {
  169. logger.error('Error in ActivityPub URLs checker.', { err })
  170. process.exit(-1)
  171. })
  172. // Email initialization
  173. Emailer.Instance.init()
  174. await Promise.all([
  175. Emailer.Instance.checkConnectionOrDie(),
  176. JobQueue.Instance.init()
  177. ])
  178. // Caches initializations
  179. VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, CACHE.PREVIEWS.MAX_AGE)
  180. VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, CACHE.VIDEO_CAPTIONS.MAX_AGE)
  181. // Enable Schedulers
  182. ActorFollowScheduler.Instance.enable()
  183. RemoveOldJobsScheduler.Instance.enable()
  184. UpdateVideosScheduler.Instance.enable()
  185. YoutubeDlUpdateScheduler.Instance.enable()
  186. VideosRedundancyScheduler.Instance.enable()
  187. // Redis initialization
  188. Redis.Instance.init()
  189. PeerTubeSocket.Instance.init(server)
  190. // Make server listening
  191. server.listen(port, hostname, () => {
  192. logger.info('Server listening on %s:%d', hostname, port)
  193. logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
  194. })
  195. process.on('exit', () => {
  196. JobQueue.Instance.terminate()
  197. })
  198. process.on('SIGINT', () => process.exit(0))
  199. }