Skip to content

Commit 648ac84

Browse files
committed
feat: check path in fs storage driver
1 parent 3232201 commit 648ac84

1 file changed

Lines changed: 12 additions & 5 deletions

File tree

lib/storage.ts

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -634,7 +634,14 @@ class FileSystemAdapter implements StorageAdapter {
634634
private rootFolder
635635

636636
constructor({ rootFolder }: { rootFolder: string }) {
637-
this.rootFolder = rootFolder
637+
this.rootFolder = path.resolve(rootFolder)
638+
}
639+
640+
private safePath(name: string) {
641+
const resolved = path.resolve(this.rootFolder, name)
642+
if (!resolved.startsWith(this.rootFolder + path.sep) && resolved !== this.rootFolder)
643+
throw new Error(`Invalid object name`)
644+
return resolved
638645
}
639646

640647
static async fromEnv(env: Extract<Env, { STORAGE_DRIVER: 'filesystem' }>) {
@@ -649,7 +656,7 @@ class FileSystemAdapter implements StorageAdapter {
649656
}
650657

651658
async createDownloadStream(objectName: string) {
652-
const filePath = path.join(this.rootFolder, objectName)
659+
const filePath = this.safePath(objectName)
653660
try {
654661
await fs.access(filePath)
655662
} catch {
@@ -659,7 +666,7 @@ class FileSystemAdapter implements StorageAdapter {
659666
}
660667

661668
async deleteFolder(folderName: string) {
662-
await fs.rm(path.join(this.rootFolder, folderName), {
669+
await fs.rm(this.safePath(folderName), {
663670
recursive: true,
664671
force: true,
665672
})
@@ -676,14 +683,14 @@ class FileSystemAdapter implements StorageAdapter {
676683
}
677684

678685
async uploadStream(objectName: string, stream: Readable) {
679-
const filePath = path.join(this.rootFolder, objectName)
686+
const filePath = this.safePath(objectName)
680687
await fs.mkdir(path.dirname(filePath), { recursive: true })
681688
await pipeline(stream, createWriteStream(filePath))
682689
}
683690

684691
async countFilesInFolder(folderName: string) {
685692
try {
686-
const dir = await fs.readdir(path.join(this.rootFolder, folderName), {
693+
const dir = await fs.readdir(this.safePath(folderName), {
687694
withFileTypes: true,
688695
})
689696
return dir.filter((item) => item.isFile()).length

0 commit comments

Comments
 (0)