1 // FIXME: https://github.com/nodejs/node/pull/16853
2 require('tls').DEFAULT_ECDH_CURVE = 'auto'
4 import { isTestInstance } from './server/helpers/core-utils'
6 if (isTestInstance()) {
7 require('source-map-support').install()
10 // ----------- Node modules -----------
11 import * as bodyParser from 'body-parser'
12 import * as express from 'express'
13 import * as morgan from 'morgan'
14 import * as cors from 'cors'
15 import * as cookieParser from 'cookie-parser'
16 import * as helmet from 'helmet'
17 import * as useragent from 'useragent'
18 import * as anonymize from 'ip-anonymize'
19 import * as cli from 'commander'
21 process.title = 'peertube'
23 // Create our main app
26 // ----------- Core checker -----------
27 import { checkMissedConfig, checkFFmpeg } from './server/initializers/checker-before-init'
29 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
30 import { logger } from './server/helpers/logger'
31 import { API_VERSION, CONFIG, CACHE, HTTP_SIGNATURE } from './server/initializers/constants'
33 const missed = checkMissedConfig()
34 if (missed.length !== 0) {
35 logger.error('Your configuration files miss keys: ' + missed)
41 logger.error('Error in ffmpeg check.', { err })
45 import { checkConfig, checkActivityPubUrls } from './server/initializers/checker-after-init'
47 const errorMessage = checkConfig()
48 if (errorMessage !== null) {
49 throw new Error(errorMessage)
52 // Trust our proxy (IP forwarding...)
53 app.set('trust proxy', CONFIG.TRUST_PROXY)
55 // Security middleware
58 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
63 // ----------- Database -----------
65 // Initialize database and models
66 import { initDatabaseModels } from './server/initializers/database'
67 import { migrate } from './server/initializers/migrator'
69 .then(() => initDatabaseModels(false))
70 .then(() => startApplication())
72 logger.error('Cannot start application.', { err })
76 // ----------- PeerTube modules -----------
77 import { installApplication } from './server/initializers'
78 import { Emailer } from './server/lib/emailer'
79 import { JobQueue } from './server/lib/job-queue'
80 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/cache'
90 createWebsocketServer, botsRouter
91 } from './server/controllers'
92 import { advertiseDoNotTrack } from './server/middlewares/dnt'
93 import { Redis } from './server/lib/redis'
94 import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
95 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
96 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
97 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
98 import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
99 import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
101 // ----------- Command line -----------
104 .option('--no-client', 'Start PeerTube without client interface')
107 // ----------- App -----------
109 // Enable CORS for develop
110 if (isTestInstance()) {
113 exposedHeaders: 'Retry-After',
118 morgan.token('remote-addr', req => {
119 return (req.get('DNT') === '1') ?
120 anonymize(req.ip || (req.connection && req.connection.remoteAddress) || undefined,
121 16, // bitmask for IPv4
122 16 // bitmask for IPv6
126 morgan.token('user-agent', req => (req.get('DNT') === '1') ?
127 useragent.parse(req.get('user-agent')).family : req.get('user-agent'))
128 app.use(morgan('combined', {
129 stream: { write: logger.info.bind(logger) }
132 app.use(bodyParser.urlencoded({ extended: false }))
133 app.use(bodyParser.json({
134 type: [ 'application/json', 'application/*+json' ],
136 verify: (req: express.Request, _, buf: Buffer, encoding: string) => {
137 const valid = isHTTPSignatureDigestValid(buf, req)
138 if (valid !== true) throw new Error('Invalid digest')
142 app.use(cookieParser())
143 // W3C DNT Tracking Status
144 app.use(advertiseDoNotTrack)
146 // ----------- Views, routes and static files -----------
149 const apiRoute = '/api/' + API_VERSION
150 app.use(apiRoute, apiRouter)
152 // Services (oembed...)
153 app.use('/services', servicesRouter)
155 app.use('/', activityPubRouter)
156 app.use('/', feedsRouter)
157 app.use('/', webfingerRouter)
158 app.use('/', trackerRouter)
159 app.use('/', botsRouter)
162 app.use('/', staticRouter)
164 // Client files, last valid routes!
165 if (cli.client) app.use('/', clientsRouter)
167 // ----------- Errors -----------
169 // Catch 404 and forward to error handler
170 app.use(function (req, res, next) {
171 const err = new Error('Not Found')
176 app.use(function (err, req, res, next) {
177 let error = 'Unknown error.'
179 error = err.stack || err.message || err
183 const sql = err.parent ? err.parent.sql : undefined
185 logger.error('Error in controller.', { err: error, sql })
186 return res.status(err.status || 500).end()
189 const server = createWebsocketServer(app)
191 // ----------- Run -----------
193 async function startApplication () {
194 const port = CONFIG.LISTEN.PORT
195 const hostname = CONFIG.LISTEN.HOSTNAME
197 await installApplication()
199 // Check activity pub urls are valid
200 checkActivityPubUrls()
202 logger.error('Error in ActivityPub URLs checker.', { err })
206 // Email initialization
207 Emailer.Instance.init()
210 Emailer.Instance.checkConnectionOrDie(),
211 JobQueue.Instance.init()
214 // Caches initializations
215 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, CACHE.PREVIEWS.MAX_AGE)
216 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, CACHE.VIDEO_CAPTIONS.MAX_AGE)
219 BadActorFollowScheduler.Instance.enable()
220 RemoveOldJobsScheduler.Instance.enable()
221 UpdateVideosScheduler.Instance.enable()
222 YoutubeDlUpdateScheduler.Instance.enable()
223 VideosRedundancyScheduler.Instance.enable()
225 // Redis initialization
226 Redis.Instance.init()
228 // Make server listening
229 server.listen(port, hostname, () => {
230 logger.info('Server listening on %s:%d', hostname, port)
231 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
234 process.on('exit', () => {
235 JobQueue.Instance.terminate()
238 process.on('SIGINT', () => process.exit(0))