diff --git a/server/storage/files/LocalStorage.ts b/server/storage/files/LocalStorage.ts index 83cf98c50e..f34f915581 100644 --- a/server/storage/files/LocalStorage.ts +++ b/server/storage/files/LocalStorage.ts @@ -8,7 +8,7 @@ import invariant from "invariant"; import JWT from "jsonwebtoken"; import safeResolvePath from "resolve-path"; import env from "@server/env"; -import { ValidationError } from "@server/errors"; +import { InternalError, ValidationError } from "@server/errors"; import Logger from "@server/logging/Logger"; import BaseStorage from "./BaseStorage"; @@ -132,8 +132,33 @@ export default class LocalStorage extends BaseStorage { }; } - public getFileStream(key: string, range?: { start: number; end: number }) { - return Promise.resolve(fs.createReadStream(this.getFilePath(key), range)); + public async getFileStream( + key: string, + range?: { start: number; end: number } + ) { + const filePath = this.getFilePath(key); + const exists = await fs.pathExists(filePath); + if (!exists) { + throw InternalError(`File not found at ${key}`); + } + + if (range) { + if ( + typeof range.start !== "number" || + typeof range.end !== "number" || + range.start < 0 || + range.end < range.start + ) { + throw ValidationError("Invalid range specified"); + } + } + + try { + return fs.createReadStream(filePath, range); + } catch (err) { + Logger.error(`Failed to create read stream`, err, { filePath }); + throw ValidationError("Unable to read file"); + } } public stat(key: string) {