@@ -4,32 +4,53 @@ import { promisify } from "util";
44import { pipeline } from "stream" ;
55import fs from "fs" ;
66import { getCorsHeaders } from "../utils" ;
7+ import { getClient } from "../auth/[...nextauth]/options" ;
78
89const pump = promisify ( pipeline ) ;
910
1011// eslint-disable-next-line import/prefer-default-export
1112export async function POST ( request : NextRequest ) {
12- const formData = await request . formData ( ) ;
13+ try {
14+ const session = await getClient ( request ) ;
1315
14- const file = formData . get ( "file" ) as File ;
16+ if ( session instanceof NextResponse ) {
17+ return session ;
18+ }
1519
16- if ( ! file ) {
17- return NextResponse . json ( { error : "No files received." } , { status : 400 , headers : getCorsHeaders ( request ) } ) ;
18- }
20+ const formData = await request . formData ( ) ;
1921
20- const filename = file . name . replaceAll ( " " , "_" ) ;
21- const filePath = path . join ( process . cwd ( ) , `public/assets/${ filename } ` ) ;
22+ const file = formData . get ( "file" ) as File ;
2223
23- try {
24- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
25- // @ts -ignore
26- await pump ( file . stream ( ) , fs . createWriteStream ( filePath ) ) ;
27- return NextResponse . json ( { path : filePath , status : 200 } , { headers : getCorsHeaders ( request ) } ) ;
28- } catch ( error ) {
29- console . error ( error ) ;
24+ if ( ! file ) {
25+ return NextResponse . json ( { error : "No files received." } , { status : 400 , headers : getCorsHeaders ( request ) } ) ;
26+ }
27+
28+ const filename = path . basename ( file . name ) . replaceAll ( " " , "_" ) ;
29+ const filePath = path . join ( process . cwd ( ) , "public" , "assets" , filename ) ;
30+
31+ // Guard against path traversal
32+ const assetsDir = path . join ( process . cwd ( ) , "public" , "assets" ) ;
33+ if ( ! filePath . startsWith ( assetsDir ) ) {
34+ return NextResponse . json ( { error : "Invalid file name." } , { status : 400 , headers : getCorsHeaders ( request ) } ) ;
35+ }
36+
37+ try {
38+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
39+ // @ts -ignore
40+ await pump ( file . stream ( ) , fs . createWriteStream ( filePath ) ) ;
41+ return NextResponse . json ( { path : filePath , status : 200 } , { headers : getCorsHeaders ( request ) } ) ;
42+ } catch ( error ) {
43+ console . error ( error ) ;
44+ return NextResponse . json (
45+ { message : ( error as Error ) . message } ,
46+ { status : 400 , headers : getCorsHeaders ( request ) }
47+ ) ;
48+ }
49+ } catch ( err ) {
50+ console . error ( err ) ;
3051 return NextResponse . json (
31- { message : ( error as Error ) . message } ,
32- { status : 400 , headers : getCorsHeaders ( request ) }
52+ { message : ( err as Error ) . message } ,
53+ { status : 500 , headers : getCorsHeaders ( request ) }
3354 ) ;
3455 }
3556}
0 commit comments