@@ -21,22 +21,43 @@ const FORM_CONTENT_TYPES = [
2121export function createOriginCheckMiddleware ( ) : MiddlewareHandler {
2222 return defineMiddleware ( ( context , next ) => {
2323 const { request, url } = context ;
24- const contentType = request . headers . get ( 'content-type' ) ;
25- if ( contentType ) {
26- if ( FORM_CONTENT_TYPES . includes ( contentType . toLowerCase ( ) ) ) {
27- const forbidden =
28- ( request . method === 'POST' ||
29- request . method === 'PUT' ||
30- request . method === 'PATCH' ||
31- request . method === 'DELETE' ) &&
32- request . headers . get ( 'origin' ) !== url . origin ;
33- if ( forbidden ) {
34- return new Response ( `Cross-site ${ request . method } form submissions are forbidden` , {
35- status : 403 ,
36- } ) ;
37- }
24+ if ( request . method === "GET" ) {
25+ return next ( ) ;
26+ }
27+ const sameOrigin =
28+ ( request . method === 'POST' ||
29+ request . method === 'PUT' ||
30+ request . method === 'PATCH' ||
31+ request . method === 'DELETE' ) &&
32+ request . headers . get ( 'origin' ) === url . origin ;
33+
34+ const hasContentType = request . headers . has ( 'content-type' )
35+ if ( hasContentType ) {
36+ const formLikeHeader = hasFormLikeHeader ( request . headers . get ( 'content-type' ) ) ;
37+ if ( formLikeHeader && ! sameOrigin ) {
38+ return new Response ( `Cross-site ${ request . method } form submissions are forbidden` , {
39+ status : 403 ,
40+ } ) ;
41+ }
42+ } else {
43+ if ( ! sameOrigin ) {
44+ return new Response ( `Cross-site ${ request . method } form submissions are forbidden` , {
45+ status : 403 ,
46+ } ) ;
3847 }
3948 }
40- return next ( ) ;
49+
50+ return next ( )
4151 } ) ;
4252}
53+
54+ function hasFormLikeHeader ( contentType : string | null ) : boolean {
55+ if ( contentType ) {
56+ for ( const FORM_CONTENT_TYPE of FORM_CONTENT_TYPES ) {
57+ if ( contentType . toLowerCase ( ) . includes ( FORM_CONTENT_TYPE ) ) {
58+ return true ;
59+ }
60+ }
61+ }
62+ return false ;
63+ }
0 commit comments