1 import express from 'express'
2 import { query } from 'express-validator'
3 import LRUCache from 'lru-cache'
4 import { basename, dirname } from 'path'
5 import { exists, isSafePeerTubeFilenameWithoutExtension, isUUIDValid, toBooleanOrNull } from '@server/helpers/custom-validators/misc'
6 import { logger } from '@server/helpers/logger'
7 import { LRU_CACHE } from '@server/initializers/constants'
8 import { VideoModel } from '@server/models/video/video'
9 import { VideoFileModel } from '@server/models/video/video-file'
10 import { MStreamingPlaylist, MVideoFile, MVideoThumbnail } from '@server/types/models'
11 import { HttpStatusCode } from '@shared/models'
12 import { areValidationErrors, checkCanAccessVideoStaticFiles } from './shared'
16 video?: MVideoThumbnail
18 playlist?: MStreamingPlaylist }
20 const staticFileTokenBypass = new LRUCache<string, LRUValue>({
21 max: LRU_CACHE.STATIC_VIDEO_FILES_RIGHTS_CHECK.MAX_SIZE,
22 ttl: LRU_CACHE.STATIC_VIDEO_FILES_RIGHTS_CHECK.TTL
25 const ensureCanAccessVideoPrivateWebTorrentFiles = [
26 query('videoFileToken').optional().custom(exists),
28 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
29 if (areValidationErrors(req, res)) return
31 const token = extractTokenOrDie(req, res)
34 const cacheKey = token + '-' + req.originalUrl
36 if (staticFileTokenBypass.has(cacheKey)) {
37 const { allowed, file, video } = staticFileTokenBypass.get(cacheKey)
39 if (allowed === true) {
40 res.locals.onlyVideo = video
41 res.locals.videoFile = file
46 return res.sendStatus(HttpStatusCode.FORBIDDEN_403)
49 const result = await isWebTorrentAllowed(req, res)
51 staticFileTokenBypass.set(cacheKey, result)
53 if (result.allowed !== true) return
55 res.locals.onlyVideo = result.video
56 res.locals.videoFile = result.file
62 const ensureCanAccessPrivateVideoHLSFiles = [
63 query('videoFileToken')
67 query('reinjectVideoFileToken')
69 .customSanitizer(toBooleanOrNull)
70 .isBoolean().withMessage('Should be a valid reinjectVideoFileToken boolean'),
74 .customSanitizer(isSafePeerTubeFilenameWithoutExtension),
76 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
77 if (areValidationErrors(req, res)) return
79 const videoUUID = basename(dirname(req.originalUrl))
81 if (!isUUIDValid(videoUUID)) {
82 logger.debug('Path does not contain valid video UUID to serve static file %s', req.originalUrl)
84 return res.sendStatus(HttpStatusCode.FORBIDDEN_403)
87 const token = extractTokenOrDie(req, res)
90 const cacheKey = token + '-' + videoUUID
92 if (staticFileTokenBypass.has(cacheKey)) {
93 const { allowed, file, playlist, video } = staticFileTokenBypass.get(cacheKey)
95 if (allowed === true) {
96 res.locals.onlyVideo = video
97 res.locals.videoFile = file
98 res.locals.videoStreamingPlaylist = playlist
103 return res.sendStatus(HttpStatusCode.FORBIDDEN_403)
106 const result = await isHLSAllowed(req, res, videoUUID)
108 staticFileTokenBypass.set(cacheKey, result)
110 if (result.allowed !== true) return
112 res.locals.onlyVideo = result.video
113 res.locals.videoFile = result.file
114 res.locals.videoStreamingPlaylist = result.playlist
121 ensureCanAccessVideoPrivateWebTorrentFiles,
122 ensureCanAccessPrivateVideoHLSFiles
125 // ---------------------------------------------------------------------------
127 async function isWebTorrentAllowed (req: express.Request, res: express.Response) {
128 const filename = basename(req.path)
130 const file = await VideoFileModel.loadWithVideoByFilename(filename)
132 logger.debug('Unknown static file %s to serve', req.originalUrl, { filename })
134 res.sendStatus(HttpStatusCode.FORBIDDEN_403)
135 return { allowed: false }
138 const video = await VideoModel.load(file.getVideo().id)
143 allowed: await checkCanAccessVideoStaticFiles({ req, res, video, paramId: video.uuid })
147 async function isHLSAllowed (req: express.Request, res: express.Response, videoUUID: string) {
148 const filename = basename(req.path)
150 const video = await VideoModel.loadWithFiles(videoUUID)
153 logger.debug('Unknown static file %s to serve', req.originalUrl, { videoUUID })
155 res.sendStatus(HttpStatusCode.FORBIDDEN_403)
156 return { allowed: false }
159 const file = await VideoFileModel.loadByFilename(filename)
164 playlist: video.getHLSPlaylist(),
165 allowed: await checkCanAccessVideoStaticFiles({ req, res, video, paramId: video.uuid })
169 function extractTokenOrDie (req: express.Request, res: express.Response) {
170 const token = res.locals.oauth?.token.accessToken || req.query.videoFileToken
174 message: 'Bearer token is missing in headers or video file token is missing in URL query parameters',
175 status: HttpStatusCode.FORBIDDEN_403