@@ -21,22 +21,43 @@ const FORM_CONTENT_TYPES = [
21
21
export function createOriginCheckMiddleware ( ) : MiddlewareHandler {
22
22
return defineMiddleware ( ( context , next ) => {
23
23
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
+ } ) ;
38
47
}
39
48
}
40
- return next ( ) ;
49
+
50
+ return next ( )
41
51
} ) ;
42
52
}
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