1- import { describe , it , expect , beforeEach , afterEach } from 'vitest' ;
21import path from 'node:path' ;
3- import { setupTestEnvironment } from '../support/helpers/setupTestEnvironment.js ' ;
2+ import { afterEach , beforeEach , describe , expect , it } from 'vitest ' ;
43import type { TestEnvironment } from '../support/helpers/setupTestEnvironment.js' ;
4+ import { setupTestEnvironment } from '../support/helpers/setupTestEnvironment.js' ;
55
66describe ( '路径遍历攻击防护' , ( ) => {
77 let env : TestEnvironment ;
@@ -52,6 +52,26 @@ describe('路径遍历攻击防护', () => {
5252 } ) ;
5353
5454 describe ( '绝对路径限制' , ( ) => {
55+ const isWithinProject = ( projectRoot : string , targetPath : string ) => {
56+ if (
57+ ! path . isAbsolute ( targetPath ) &&
58+ path . win32 . isAbsolute ( targetPath ) &&
59+ process . platform !== 'win32'
60+ ) {
61+ return false ;
62+ }
63+
64+ const resolvedProject = path . resolve ( projectRoot ) ;
65+ const resolvedTarget = path . resolve ( targetPath ) ;
66+ const projectPrefix = resolvedProject . endsWith ( path . sep )
67+ ? resolvedProject
68+ : `${ resolvedProject } ${ path . sep } ` ;
69+
70+ return (
71+ resolvedTarget === resolvedProject || resolvedTarget . startsWith ( projectPrefix )
72+ ) ;
73+ } ;
74+
5575 it ( '应该检测项目目录外的绝对路径' , ( ) => {
5676 const projectRoot = env . projectDir ;
5777 const outsidePaths = [
@@ -62,9 +82,7 @@ describe('路径遍历攻击防护', () => {
6282 ] ;
6383
6484 for ( const outsidePath of outsidePaths ) {
65- const resolvedPath = path . resolve ( outsidePath ) ;
66- const isWithinProject = resolvedPath . startsWith ( projectRoot ) ;
67- expect ( isWithinProject ) . toBe ( false ) ;
85+ expect ( isWithinProject ( projectRoot , outsidePath ) ) . toBe ( false ) ;
6886 }
6987 } ) ;
7088
@@ -77,8 +95,7 @@ describe('路径遍历攻击防护', () => {
7795 ] ;
7896
7997 for ( const insidePath of insidePaths ) {
80- const isWithinProject = insidePath . startsWith ( projectRoot ) ;
81- expect ( isWithinProject ) . toBe ( true ) ;
98+ expect ( isWithinProject ( projectRoot , insidePath ) ) . toBe ( true ) ;
8299 }
83100 } ) ;
84101 } ) ;
0 commit comments