server.ts 7.9 KB

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