Merge branch 'move-utils-to-shared' of https://github.com/buoyantair/PeerTube into...
[oweals/peertube.git] / server.ts
1 // FIXME: https://github.com/nodejs/node/pull/16853
2 require('tls').DEFAULT_ECDH_CURVE = 'auto'
3
4 import { isTestInstance } from './server/helpers/core-utils'
5
6 if (isTestInstance()) {
7   require('source-map-support').install()
8 }
9
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'
20
21 process.title = 'peertube'
22
23 // Create our main app
24 const app = express()
25
26 // ----------- Core checker -----------
27 import { checkMissedConfig, checkFFmpeg } from './server/initializers/checker-before-init'
28
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'
32
33 const missed = checkMissedConfig()
34 if (missed.length !== 0) {
35   logger.error('Your configuration files miss keys: ' + missed)
36   process.exit(-1)
37 }
38
39 checkFFmpeg(CONFIG)
40   .catch(err => {
41     logger.error('Error in ffmpeg check.', { err })
42     process.exit(-1)
43   })
44
45 import { checkConfig, checkActivityPubUrls } from './server/initializers/checker-after-init'
46
47 const errorMessage = checkConfig()
48 if (errorMessage !== null) {
49   throw new Error(errorMessage)
50 }
51
52 // Trust our proxy (IP forwarding...)
53 app.set('trust proxy', CONFIG.TRUST_PROXY)
54
55 // Security middleware
56 app.use(helmet({
57   frameguard: {
58     action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
59   },
60   hsts: false
61 }))
62
63 // ----------- Database -----------
64
65 // Initialize database and models
66 import { initDatabaseModels } from './server/initializers/database'
67 import { migrate } from './server/initializers/migrator'
68 migrate()
69   .then(() => initDatabaseModels(false))
70   .then(() => startApplication())
71   .catch(err => {
72     logger.error('Cannot start application.', { err })
73     process.exit(-1)
74   })
75
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'
81 import {
82   activityPubRouter,
83   apiRouter,
84   clientsRouter,
85   feedsRouter,
86   staticRouter,
87   servicesRouter,
88   webfingerRouter,
89   trackerRouter,
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'
100
101 // ----------- Command line -----------
102
103 cli
104   .option('--no-client', 'Start PeerTube without client interface')
105   .parse(process.argv)
106
107 // ----------- App -----------
108
109 // Enable CORS for develop
110 if (isTestInstance()) {
111   app.use(cors({
112     origin: '*',
113     exposedHeaders: 'Retry-After',
114     credentials: true
115   }))
116 }
117 // For the logger
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
123     ) :
124     req.ip
125 })
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) }
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, encoding: string) => {
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
146 // ----------- Views, routes and static files -----------
147
148 // API
149 const apiRoute = '/api/' + API_VERSION
150 app.use(apiRoute, apiRouter)
151
152 // Services (oembed...)
153 app.use('/services', servicesRouter)
154
155 app.use('/', activityPubRouter)
156 app.use('/', feedsRouter)
157 app.use('/', webfingerRouter)
158 app.use('/', trackerRouter)
159 app.use('/', botsRouter)
160
161 // Static files
162 app.use('/', staticRouter)
163
164 // Client files, last valid routes!
165 if (cli.client) app.use('/', clientsRouter)
166
167 // ----------- Errors -----------
168
169 // Catch 404 and forward to error handler
170 app.use(function (req, res, next) {
171   const err = new Error('Not Found')
172   err['status'] = 404
173   next(err)
174 })
175
176 app.use(function (err, req, res, next) {
177   let error = 'Unknown error.'
178   if (err) {
179     error = err.stack || err.message || err
180   }
181
182   // Sequelize error
183   const sql = err.parent ? err.parent.sql : undefined
184
185   logger.error('Error in controller.', { err: error, sql })
186   return res.status(err.status || 500).end()
187 })
188
189 const server = createWebsocketServer(app)
190
191 // ----------- Run -----------
192
193 async function startApplication () {
194   const port = CONFIG.LISTEN.PORT
195   const hostname = CONFIG.LISTEN.HOSTNAME
196
197   await installApplication()
198
199   // Check activity pub urls are valid
200   checkActivityPubUrls()
201     .catch(err => {
202       logger.error('Error in ActivityPub URLs checker.', { err })
203       process.exit(-1)
204     })
205
206   // Email initialization
207   Emailer.Instance.init()
208
209   await Promise.all([
210     Emailer.Instance.checkConnectionOrDie(),
211     JobQueue.Instance.init()
212   ])
213
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)
217
218   // Enable Schedulers
219   BadActorFollowScheduler.Instance.enable()
220   RemoveOldJobsScheduler.Instance.enable()
221   UpdateVideosScheduler.Instance.enable()
222   YoutubeDlUpdateScheduler.Instance.enable()
223   VideosRedundancyScheduler.Instance.enable()
224
225   // Redis initialization
226   Redis.Instance.init()
227
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)
232   })
233
234   process.on('exit', () => {
235     JobQueue.Instance.terminate()
236   })
237
238   process.on('SIGINT', () => process.exit(0))
239 }