Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

prevent potential directory traversal

Blue Mouse0d6c4b8b41b2
diff --git a/apps/production/src/blog/blog.service.ts b/apps/production/src/blog/blog.service.ts
index b66b2f23c..91b01d177 100644
--- a/apps/production/src/blog/blog.service.ts
+++ b/apps/production/src/blog/blog.service.ts
@@ -11,7 +11,7 @@ import * as _size from 'lodash/size'
import * as path from 'path'
import * as fs from 'fs/promises'
import { AppLoggerService } from '../logger/logger.service'
-import { BLOG_POSTS_PATH, redis } from '../common/constants'
+import { BLOG_POSTS_PATH, BLOG_POSTS_ROOT, redis } from '../common/constants'
// eslint-disable-next-line
const parseFrontMatter = require('front-matter')
@@ -34,14 +34,22 @@ interface IParseFontMatter {
body: string
}
+const validatePath = (input: string) => {
+ if (!_includes(path.normalize(input), BLOG_POSTS_ROOT)) {
+ throw new Error('You are not allowed to access this file')
+ }
+}
+
const getFileNames = async (category?: string): Promise<string[]> => {
let files
try {
if (category) {
- files = (await fs.readdir(
- path.join(BLOG_POSTS_PATH, category),
- )) as string[]
+ const pathToRead = path.join(BLOG_POSTS_PATH, category)
+
+ validatePath(pathToRead)
+
+ files = (await fs.readdir(pathToRead)) as string[]
} else {
files = (await fs.readdir(BLOG_POSTS_PATH)) as string[]
}
diff --git a/apps/production/src/common/constants.ts b/apps/production/src/common/constants.ts
index dd4c841f3..f40571f02 100644
--- a/apps/production/src/common/constants.ts
+++ b/apps/production/src/common/constants.ts
@@ -115,6 +115,8 @@ const CAPTCHA_SECRET_KEY_LENGTH = 50
const MIN_PAGES_IN_FUNNEL = 2
const MAX_PAGES_IN_FUNNEL = 10
+const BLOG_POSTS_ROOT = 'blog-posts/posts'
+
const BLOG_POSTS_PATH = isDevelopment
? path.join(__dirname, '../../../..', 'blog-posts', 'posts')
: path.join(__dirname, '../..', 'blog-posts', 'posts')
@@ -228,4 +230,5 @@ export {
MAX_PAGES_IN_FUNNEL,
MAX_FUNNELS,
ALL_COLUMNS,
+ BLOG_POSTS_ROOT,
}