]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server.ts
a688bb5d082a108ecee908a4366c1d2f39b690df
[github/Chocobozzz/PeerTube.git] / server.ts
1 // FIXME: https://github.com/nodejs/node/pull/16853
2 import { VideosCaptionCache } from './server/lib/cache/videos-caption-cache'
3
4 require('tls').DEFAULT_ECDH_CURVE = 'auto'
5
6 import { isTestInstance } from './server/helpers/core-utils'
7
8 if (isTestInstance()) {
9 require('source-map-support').install()
10 }
11
12 // ----------- Node modules -----------
13 import * as bodyParser from 'body-parser'
14 import * as express from 'express'
15 import * as morgan from 'morgan'
16 import * as cors from 'cors'
17 import * as cookieParser from 'cookie-parser'
18 import * as helmet from 'helmet'
19
20 process.title = 'peertube'
21
22 // Create our main app
23 const app = express()
24
25 // ----------- Core checker -----------
26 import { checkMissedConfig, checkFFmpeg, checkConfig, checkActivityPubUrls } from './server/initializers/checker'
27
28 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
29 import { logger } from './server/helpers/logger'
30 import { API_VERSION, CONFIG, STATIC_PATHS, CACHE } from './server/initializers/constants'
31
32 const missed = checkMissedConfig()
33 if (missed.length !== 0) {
34 logger.error('Your configuration files miss keys: ' + missed)
35 process.exit(-1)
36 }
37
38 checkFFmpeg(CONFIG)
39 .catch(err => {
40 logger.error('Error in ffmpeg check.', { err })
41 process.exit(-1)
42 })
43
44 const errorMessage = checkConfig()
45 if (errorMessage !== null) {
46 throw new Error(errorMessage)
47 }
48
49 // Trust our proxy (IP forwarding...)
50 app.set('trust proxy', CONFIG.TRUST_PROXY)
51
52 // Security middlewares
53 app.use(helmet({
54 frameguard: {
55 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
56 },
57 dnsPrefetchControl: {
58 allow: true
59 },
60 contentSecurityPolicy: {
61 directives: {
62 fontSrc: ["'self'"],
63 frameSrc: ["'none'"],
64 mediaSrc: ['*', 'https:'],
65 objectSrc: ["'none'"],
66 scriptSrc: ["'self'"],
67 styleSrc: ["'self'"],
68 upgradeInsecureRequests: true
69 },
70 browserSniff: false // assumes a modern browser, but allows CDN in front
71 },
72 referrerPolicy: {
73 policy: 'strict-origin-when-cross-origin'
74 }
75 }))
76
77 // ----------- Database -----------
78
79 // Initialize database and models
80 import { initDatabaseModels } from './server/initializers/database'
81 import { migrate } from './server/initializers/migrator'
82 migrate()
83 .then(() => initDatabaseModels(false))
84 .then(() => startApplication())
85 .catch(err => {
86 logger.error('Cannot start application.', { err })
87 process.exit(-1)
88 })
89
90 // ----------- PeerTube modules -----------
91 import { installApplication } from './server/initializers'
92 import { Emailer } from './server/lib/emailer'
93 import { JobQueue } from './server/lib/job-queue'
94 import { VideosPreviewCache } from './server/lib/cache'
95 import {
96 activityPubRouter,
97 apiRouter,
98 clientsRouter,
99 feedsRouter,
100 staticRouter,
101 servicesRouter,
102 webfingerRouter,
103 trackerRouter,
104 createWebsocketServer
105 } from './server/controllers'
106 import { Redis } from './server/lib/redis'
107 import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
108 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
109 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
110
111 // ----------- Command line -----------
112
113 // ----------- App -----------
114
115 // Enable CORS for develop
116 if (isTestInstance()) {
117 app.use((req, res, next) => {
118 // These routes have already cors
119 if (
120 req.path.indexOf(STATIC_PATHS.TORRENTS) === -1 &&
121 req.path.indexOf(STATIC_PATHS.WEBSEED) === -1 &&
122 req.path.startsWith('/api/') === false
123 ) {
124 return (cors({
125 origin: '*',
126 exposedHeaders: 'Retry-After',
127 credentials: true
128 }))(req, res, next)
129 }
130
131 return next()
132 })
133 }
134
135 // For the logger
136 app.use(morgan('combined', {
137 stream: { write: logger.info.bind(logger) }
138 }))
139 // For body requests
140 app.use(bodyParser.urlencoded({ extended: false }))
141 app.use(bodyParser.json({
142 type: [ 'application/json', 'application/*+json' ],
143 limit: '500kb'
144 }))
145 // Cookies
146 app.use(cookieParser())
147
148 // ----------- Views, routes and static files -----------
149
150 // API
151 const apiRoute = '/api/' + API_VERSION
152 app.use(apiRoute, apiRouter)
153
154 // Services (oembed...)
155 app.use('/services', servicesRouter)
156
157 app.use('/', activityPubRouter)
158 app.use('/', feedsRouter)
159 app.use('/', webfingerRouter)
160 app.use('/', trackerRouter)
161
162 // Static files
163 app.use('/', staticRouter)
164
165 // Client files, last valid routes!
166 app.use('/', clientsRouter)
167
168 // ----------- Errors -----------
169
170 // Catch 404 and forward to error handler
171 app.use(function (req, res, next) {
172 const err = new Error('Not Found')
173 err['status'] = 404
174 next(err)
175 })
176
177 app.use(function (err, req, res, next) {
178 let error = 'Unknown error.'
179 if (err) {
180 error = err.stack || err.message || err
181 }
182
183 logger.error('Error in controller.', { error })
184 return res.status(err.status || 500).end()
185 })
186
187 const server = createWebsocketServer(app)
188
189 // ----------- Run -----------
190
191 async function startApplication () {
192 const port = CONFIG.LISTEN.PORT
193 const hostname = CONFIG.LISTEN.HOSTNAME
194
195 await installApplication()
196
197 // Check activity pub urls are valid
198 checkActivityPubUrls()
199 .catch(err => {
200 logger.error('Error in ActivityPub URLs checker.', { err })
201 process.exit(-1)
202 })
203
204 // Email initialization
205 Emailer.Instance.init()
206 await Emailer.Instance.checkConnectionOrDie()
207
208 await JobQueue.Instance.init()
209
210 // Caches initializations
211 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, CACHE.PREVIEWS.MAX_AGE)
212 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, CACHE.VIDEO_CAPTIONS.MAX_AGE)
213
214 // Enable Schedulers
215 BadActorFollowScheduler.Instance.enable()
216 RemoveOldJobsScheduler.Instance.enable()
217 UpdateVideosScheduler.Instance.enable()
218
219 // Redis initialization
220 Redis.Instance.init()
221
222 // Make server listening
223 server.listen(port, hostname, () => {
224 logger.info('Server listening on %s:%d', hostname, port)
225 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
226 })
227 }