fix: path traversal vulnerability, #851 (#855)

* Fix Path Traversal fallback

* Update loader.ts

Fixed nested

* Update loader.ts

padding fix

* refactor: reuse root enforcing

* docs: update test case and docs

---------

Co-authored-by: MorielHarush <[email protected]>
This commit is contained in:
Yang Jun
2026-03-08 02:36:09 +08:00
committed by GitHub
co-authored by MorielHarush
parent 85233e0568
commit 3cd024d652
11 changed files with 47 additions and 33 deletions
+12 -11
View File
@@ -43,25 +43,26 @@ export class Loader {
public * candidates (file: string, dirs: string[], currentFile?: string, enforceRoot?: boolean) {
const { fs, extname } = this.options
const isAllowed = (filepath: string) => {
if (!enforceRoot) return true
for (const dir of dirs) {
if (this.contains(dir, filepath)) return true
}
return false
}
if (this.shouldLoadRelative(file) && currentFile) {
const referenced = fs.resolve(this.dirname(currentFile), file, extname)
for (const dir of dirs) {
if (!enforceRoot || this.contains(dir, referenced)) {
// the relatively referenced file is within one of root dirs
yield referenced
break
}
}
if (isAllowed(referenced)) yield referenced
}
for (const dir of dirs) {
const referenced = fs.resolve(dir, file, extname)
if (!enforceRoot || this.contains(dir, referenced)) {
yield referenced
}
if (isAllowed(referenced)) yield referenced
}
if (fs.fallback !== undefined) {
const filepath = fs.fallback(file)
if (filepath !== undefined) yield filepath
if (filepath !== undefined && isAllowed(filepath)) yield filepath
}
}