]>
Commit | Line | Data |
---|---|---|
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 | |
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 | ||
160 | // Static files | |
161 | app.use('/', staticRouter) | |
162 | ||
163 | // Client files, last valid routes! | |
164 | if (cli.client) app.use('/', clientsRouter) | |
165 | ||
166 | // ----------- Errors ----------- | |
167 | ||
168 | // Catch 404 and forward to error handler | |
169 | app.use(function (req, res, next) { | |
170 | const err = new Error('Not Found') | |
171 | err['status'] = 404 | |
172 | next(err) | |
173 | }) | |
174 | ||
175 | app.use(function (err, req, res, next) { | |
176 | let error = 'Unknown error.' | |
177 | if (err) { | |
178 | error = err.stack || err.message || err | |
179 | } | |
180 | ||
181 | // Sequelize error | |
182 | const sql = err.parent ? err.parent.sql : undefined | |
183 | ||
184 | logger.error('Error in controller.', { err: error, sql }) | |
185 | return res.status(err.status || 500).end() | |
186 | }) | |
187 | ||
188 | const server = createWebsocketServer(app) | |
189 | ||
190 | // ----------- Run ----------- | |
191 | ||
192 | async function startApplication () { | |
193 | const port = CONFIG.LISTEN.PORT | |
194 | const hostname = CONFIG.LISTEN.HOSTNAME | |
195 | ||
196 | await installApplication() | |
197 | ||
198 | // Check activity pub urls are valid | |
199 | checkActivityPubUrls() | |
200 | .catch(err => { | |
201 | logger.error('Error in ActivityPub URLs checker.', { err }) | |
202 | process.exit(-1) | |
203 | }) | |
204 | ||
205 | // Email initialization | |
206 | Emailer.Instance.init() | |
207 | ||
208 | await Promise.all([ | |
209 | Emailer.Instance.checkConnectionOrDie(), | |
210 | JobQueue.Instance.init() | |
211 | ]) | |
212 | ||
213 | // Caches initializations | |
214 | VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, CACHE.PREVIEWS.MAX_AGE) | |
215 | VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, CACHE.VIDEO_CAPTIONS.MAX_AGE) | |
216 | ||
217 | // Enable Schedulers | |
218 | BadActorFollowScheduler.Instance.enable() | |
219 | RemoveOldJobsScheduler.Instance.enable() | |
220 | UpdateVideosScheduler.Instance.enable() | |
221 | YoutubeDlUpdateScheduler.Instance.enable() | |
222 | VideosRedundancyScheduler.Instance.enable() | |
223 | ||
224 | // Redis initialization | |
225 | Redis.Instance.init() | |
226 | ||
227 | // Make server listening | |
228 | server.listen(port, hostname, () => { | |
229 | logger.info('Server listening on %s:%d', hostname, port) | |
230 | logger.info('Web server: %s', CONFIG.WEBSERVER.URL) | |
231 | }) | |
232 | ||
233 | process.on('exit', () => { | |
234 | JobQueue.Instance.terminate() | |
235 | }) | |
236 | ||
237 | process.on('SIGINT', () => process.exit(0)) | |
238 | } |