]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server.ts
Improve frontend accessibility
[github/Chocobozzz/PeerTube.git] / server.ts
CommitLineData
6b467fd5 1// FIXME: https://github.com/nodejs/node/pull/16853
40e87e9e
C
2import { VideosCaptionCache } from './server/lib/cache/videos-caption-cache'
3
6b467fd5
C
4require('tls').DEFAULT_ECDH_CURVE = 'auto'
5
1840c2f7
C
6import { isTestInstance } from './server/helpers/core-utils'
7
8if (isTestInstance()) {
e02643f3
C
9 require('source-map-support').install()
10}
11
a030a9b2 12// ----------- Node modules -----------
4d4e5cd4
C
13import * as bodyParser from 'body-parser'
14import * as express from 'express'
4d4e5cd4 15import * as morgan from 'morgan'
1840c2f7 16import * as cors from 'cors'
8afc19a6 17import * as cookieParser from 'cookie-parser'
d00e2393 18import * as helmet from 'helmet'
a030a9b2 19
9f540774
C
20process.title = 'peertube'
21
a030a9b2 22// Create our main app
13ce1d01 23const app = express()
a030a9b2 24
3482688c 25// ----------- Core checker -----------
23687332 26import { checkMissedConfig, checkFFmpeg, checkConfig, checkActivityPubUrls } from './server/initializers/checker'
69b0a27c 27
d5b7d911
C
28// Do not use barrels because we don't want to load all modules here (we need to initialize database first)
29import { logger } from './server/helpers/logger'
f4001cf4 30import { API_VERSION, CONFIG, STATIC_PATHS, CACHE } from './server/initializers/constants'
d5b7d911 31
65fcc311 32const missed = checkMissedConfig()
b65c27aa 33if (missed.length !== 0) {
d5b7d911
C
34 logger.error('Your configuration files miss keys: ' + missed)
35 process.exit(-1)
b65c27aa 36}
3482688c 37
3482688c 38checkFFmpeg(CONFIG)
d5b7d911
C
39 .catch(err => {
40 logger.error('Error in ffmpeg check.', { err })
41 process.exit(-1)
42 })
b65c27aa 43
65fcc311 44const errorMessage = checkConfig()
b65c27aa
C
45if (errorMessage !== null) {
46 throw new Error(errorMessage)
69b0a27c
C
47}
48
490b595a
C
49// Trust our proxy (IP forwarding...)
50app.set('trust proxy', CONFIG.TRUST_PROXY)
51
d00e2393
RK
52// Security middlewares
53app.use(helmet({
54 frameguard: {
4bdd9473
RK
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'
d00e2393
RK
74 }
75}))
76
3482688c 77// ----------- Database -----------
91fea9fc 78
3482688c 79// Initialize database and models
91fea9fc
C
80import { initDatabaseModels } from './server/initializers/database'
81import { migrate } from './server/initializers/migrator'
82migrate()
83 .then(() => initDatabaseModels(false))
3d3441d6
C
84 .then(() => startApplication())
85 .catch(err => {
86 logger.error('Cannot start application.', { err })
87 process.exit(-1)
88 })
3482688c 89
00057e85 90// ----------- PeerTube modules -----------
91fea9fc 91import { installApplication } from './server/initializers'
ecb4e35f 92import { Emailer } from './server/lib/emailer'
94a5ff8a 93import { JobQueue } from './server/lib/job-queue'
50d6de9c 94import { VideosPreviewCache } from './server/lib/cache'
244e76a5
RK
95import {
96 activityPubRouter,
97 apiRouter,
98 clientsRouter,
99 feedsRouter,
100 staticRouter,
101 servicesRouter,
9b67da3d
C
102 webfingerRouter,
103 trackerRouter,
104 createWebsocketServer
244e76a5 105} from './server/controllers'
ecb4e35f 106import { Redis } from './server/lib/redis'
60650c77 107import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
94a5ff8a 108import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
2baea0c7 109import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
a030a9b2 110
a030a9b2
C
111// ----------- Command line -----------
112
113// ----------- App -----------
114
12daa837
WL
115// Enable CORS for develop
116if (isTestInstance()) {
117 app.use((req, res, next) => {
118 // These routes have already cors
119 if (
120 req.path.indexOf(STATIC_PATHS.TORRENTS) === -1 &&
3ff5a19b
C
121 req.path.indexOf(STATIC_PATHS.WEBSEED) === -1 &&
122 req.path.startsWith('/api/') === false
12daa837
WL
123 ) {
124 return (cors({
125 origin: '*',
126 exposedHeaders: 'Retry-After',
127 credentials: true
128 }))(req, res, next)
129 }
130
131 return next()
132 })
133}
1840c2f7 134
a030a9b2 135// For the logger
e02643f3 136app.use(morgan('combined', {
23e27dd5 137 stream: { write: logger.info.bind(logger) }
e02643f3 138}))
a030a9b2 139// For body requests
bf9ae5ce 140app.use(bodyParser.urlencoded({ extended: false }))
165cdc75 141app.use(bodyParser.json({
86d13ec2 142 type: [ 'application/json', 'application/*+json' ],
165cdc75
C
143 limit: '500kb'
144}))
8afc19a6
C
145// Cookies
146app.use(cookieParser())
a030a9b2 147
a96aed15
C
148// ----------- Views, routes and static files -----------
149
150// API
151const apiRoute = '/api/' + API_VERSION
152app.use(apiRoute, apiRouter)
153
154// Services (oembed...)
155app.use('/services', servicesRouter)
156
350e31d6 157app.use('/', activityPubRouter)
244e76a5
RK
158app.use('/', feedsRouter)
159app.use('/', webfingerRouter)
9b67da3d 160app.use('/', trackerRouter)
350e31d6 161
a96aed15
C
162// Static files
163app.use('/', staticRouter)
164
989e526a
C
165// Client files, last valid routes!
166app.use('/', clientsRouter)
a96aed15 167
a030a9b2
C
168// ----------- Errors -----------
169
170// Catch 404 and forward to error handler
171app.use(function (req, res, next) {
13ce1d01 172 const err = new Error('Not Found')
65fcc311 173 err['status'] = 404
a030a9b2
C
174 next(err)
175})
176
6f4e2522 177app.use(function (err, req, res, next) {
e3a682a8
C
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()
6f4e2522 185})
a030a9b2 186
9b67da3d
C
187const server = createWebsocketServer(app)
188
79530164
C
189// ----------- Run -----------
190
3d3441d6 191async function startApplication () {
65fcc311 192 const port = CONFIG.LISTEN.PORT
cff8b272 193 const hostname = CONFIG.LISTEN.HOSTNAME
91fea9fc 194
3d3441d6
C
195 await installApplication()
196
23687332
C
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
3d3441d6
C
204 // Email initialization
205 Emailer.Instance.init()
206 await Emailer.Instance.checkConnectionOrDie()
207
208 await JobQueue.Instance.init()
209
210 // Caches initializations
f4001cf4
C
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)
3d3441d6
C
213
214 // Enable Schedulers
215 BadActorFollowScheduler.Instance.enable()
216 RemoveOldJobsScheduler.Instance.enable()
2baea0c7 217 UpdateVideosScheduler.Instance.enable()
3d3441d6
C
218
219 // Redis initialization
220 Redis.Instance.init()
221
222 // Make server listening
f55e5a7b
C
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 })
5804c0db 227}