]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server.ts
Fix UI regressions
[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'
57bf30a9 30import { API_VERSION, CONFIG, STATIC_PATHS, CACHE, REMOTE_SCHEME } 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
57c36b27 52// Security middleware
d00e2393
RK
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: {
57bf30a9 62 defaultSrc: ['*', 'data:', REMOTE_SCHEME.WS + ':', REMOTE_SCHEME.HTTP + ':'],
aa1c3d92 63 fontSrc: ["'self'", 'data:'],
4bdd9473 64 frameSrc: ["'none'"],
57bf30a9 65 mediaSrc: ['*', REMOTE_SCHEME.HTTP + ':'],
4bdd9473 66 objectSrc: ["'none'"],
aa1c3d92
RK
67 scriptSrc: ["'self'", "'unsafe-inline'", "'unsafe-eval'"],
68 styleSrc: ["'self'", "'unsafe-inline'"],
57bf30a9 69 upgradeInsecureRequests: false
4bdd9473
RK
70 },
71 browserSniff: false // assumes a modern browser, but allows CDN in front
72 },
73 referrerPolicy: {
74 policy: 'strict-origin-when-cross-origin'
d00e2393
RK
75 }
76}))
aa1c3d92
RK
77app.use((_, res, next) => {
78 [
79 "vibrate 'none'",
80 "geolocation 'none'",
81 "camera 'none'",
82 "microphone 'none'",
83 "magnetometer 'none'",
84 "payment 'none'",
85 "accelerometer 'none'"
86 ].forEach(e => res.append('Feature-Policy', e + ';'))
87 next()
88})
d00e2393 89
3482688c 90// ----------- Database -----------
91fea9fc 91
3482688c 92// Initialize database and models
91fea9fc
C
93import { initDatabaseModels } from './server/initializers/database'
94import { migrate } from './server/initializers/migrator'
95migrate()
96 .then(() => initDatabaseModels(false))
3d3441d6
C
97 .then(() => startApplication())
98 .catch(err => {
99 logger.error('Cannot start application.', { err })
100 process.exit(-1)
101 })
3482688c 102
00057e85 103// ----------- PeerTube modules -----------
91fea9fc 104import { installApplication } from './server/initializers'
ecb4e35f 105import { Emailer } from './server/lib/emailer'
94a5ff8a 106import { JobQueue } from './server/lib/job-queue'
50d6de9c 107import { VideosPreviewCache } from './server/lib/cache'
244e76a5
RK
108import {
109 activityPubRouter,
110 apiRouter,
111 clientsRouter,
112 feedsRouter,
113 staticRouter,
114 servicesRouter,
9b67da3d
C
115 webfingerRouter,
116 trackerRouter,
117 createWebsocketServer
244e76a5 118} from './server/controllers'
ecb4e35f 119import { Redis } from './server/lib/redis'
60650c77 120import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
94a5ff8a 121import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
2baea0c7 122import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
a030a9b2 123
a030a9b2
C
124// ----------- Command line -----------
125
126// ----------- App -----------
127
12daa837
WL
128// Enable CORS for develop
129if (isTestInstance()) {
62945f06
C
130 app.use(cors({
131 origin: '*',
132 exposedHeaders: 'Retry-After',
133 credentials: true
134 }))
12daa837 135}
1840c2f7 136
a030a9b2 137// For the logger
e02643f3 138app.use(morgan('combined', {
23e27dd5 139 stream: { write: logger.info.bind(logger) }
e02643f3 140}))
a030a9b2 141// For body requests
bf9ae5ce 142app.use(bodyParser.urlencoded({ extended: false }))
165cdc75 143app.use(bodyParser.json({
86d13ec2 144 type: [ 'application/json', 'application/*+json' ],
165cdc75
C
145 limit: '500kb'
146}))
8afc19a6
C
147// Cookies
148app.use(cookieParser())
a030a9b2 149
a96aed15
C
150// ----------- Views, routes and static files -----------
151
152// API
153const apiRoute = '/api/' + API_VERSION
154app.use(apiRoute, apiRouter)
155
156// Services (oembed...)
157app.use('/services', servicesRouter)
158
350e31d6 159app.use('/', activityPubRouter)
244e76a5
RK
160app.use('/', feedsRouter)
161app.use('/', webfingerRouter)
9b67da3d 162app.use('/', trackerRouter)
350e31d6 163
a96aed15
C
164// Static files
165app.use('/', staticRouter)
166
989e526a
C
167// Client files, last valid routes!
168app.use('/', clientsRouter)
a96aed15 169
a030a9b2
C
170// ----------- Errors -----------
171
172// Catch 404 and forward to error handler
173app.use(function (req, res, next) {
13ce1d01 174 const err = new Error('Not Found')
65fcc311 175 err['status'] = 404
a030a9b2
C
176 next(err)
177})
178
6f4e2522 179app.use(function (err, req, res, next) {
e3a682a8
C
180 let error = 'Unknown error.'
181 if (err) {
182 error = err.stack || err.message || err
183 }
184
185 logger.error('Error in controller.', { error })
186 return res.status(err.status || 500).end()
6f4e2522 187})
a030a9b2 188
9b67da3d
C
189const server = createWebsocketServer(app)
190
79530164
C
191// ----------- Run -----------
192
3d3441d6 193async function startApplication () {
65fcc311 194 const port = CONFIG.LISTEN.PORT
cff8b272 195 const hostname = CONFIG.LISTEN.HOSTNAME
91fea9fc 196
3d3441d6
C
197 await installApplication()
198
23687332
C
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
3d3441d6
C
206 // Email initialization
207 Emailer.Instance.init()
208 await Emailer.Instance.checkConnectionOrDie()
209
210 await JobQueue.Instance.init()
211
212 // Caches initializations
f4001cf4
C
213 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, CACHE.PREVIEWS.MAX_AGE)
214 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, CACHE.VIDEO_CAPTIONS.MAX_AGE)
3d3441d6
C
215
216 // Enable Schedulers
217 BadActorFollowScheduler.Instance.enable()
218 RemoveOldJobsScheduler.Instance.enable()
2baea0c7 219 UpdateVideosScheduler.Instance.enable()
3d3441d6
C
220
221 // Redis initialization
222 Redis.Instance.init()
223
224 // Make server listening
f55e5a7b
C
225 server.listen(port, hostname, () => {
226 logger.info('Server listening on %s:%d', hostname, port)
227 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
228 })
5804c0db 229}