server.ts 8.0 KB

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