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