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, 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'),
72 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
73 if (areValidationErrors(req, res)) return
75 const videoUUID = basename(dirname(req.originalUrl))
77 if (!isUUIDValid(videoUUID)) {
78 logger.debug('Path does not contain valid video UUID to serve static file %s', req.originalUrl)
80 return res.sendStatus(HttpStatusCode.FORBIDDEN_403)
83 const token = extractTokenOrDie(req, res)
86 const cacheKey = token + '-' + videoUUID
88 if (staticFileTokenBypass.has(cacheKey)) {
89 const { allowed, file, playlist, video } = staticFileTokenBypass.get(cacheKey)
91 if (allowed === true) {
92 res.locals.onlyVideo = video
93 res.locals.videoFile = file
94 res.locals.videoStreamingPlaylist = playlist
99 return res.sendStatus(HttpStatusCode.FORBIDDEN_403)
102 const result = await isHLSAllowed(req, res, videoUUID)
104 staticFileTokenBypass.set(cacheKey, result)
106 if (result.allowed !== true) return
108 res.locals.onlyVideo = result.video
109 res.locals.videoFile = result.file
110 res.locals.videoStreamingPlaylist = result.playlist
117 ensureCanAccessVideoPrivateWebTorrentFiles,
118 ensureCanAccessPrivateVideoHLSFiles
121 // ---------------------------------------------------------------------------
123 async function isWebTorrentAllowed (req: express.Request, res: express.Response) {
124 const filename = basename(req.path)
126 const file = await VideoFileModel.loadWithVideoByFilename(filename)
128 logger.debug('Unknown static file %s to serve', req.originalUrl, { filename })
130 res.sendStatus(HttpStatusCode.FORBIDDEN_403)
131 return { allowed: false }
134 const video = await VideoModel.load(file.getVideo().id)
139 allowed: await checkCanAccessVideoStaticFiles({ req, res, video, paramId: video.uuid })
143 async function isHLSAllowed (req: express.Request, res: express.Response, videoUUID: string) {
144 const filename = basename(req.path)
146 const video = await VideoModel.loadWithFiles(videoUUID)
149 logger.debug('Unknown static file %s to serve', req.originalUrl, { videoUUID })
151 res.sendStatus(HttpStatusCode.FORBIDDEN_403)
152 return { allowed: false }
155 const file = await VideoFileModel.loadByFilename(filename)
160 playlist: video.getHLSPlaylist(),
161 allowed: await checkCanAccessVideoStaticFiles({ req, res, video, paramId: video.uuid })
165 function extractTokenOrDie (req: express.Request, res: express.Response) {
166 const token = res.locals.oauth?.token.accessToken || req.query.videoFileToken
170 message: 'Bearer token is missing in headers or video file token is missing in URL query parameters',
171 status: HttpStatusCode.FORBIDDEN_403