22import type { Middleware , NextHandler , Request } from 'jitar' ;
33import { BadRequest , type Response } from 'jitar' ;
44
5+ import type { ValidationSchema } from '^/integrations/validation' ;
6+ import validator from '^/integrations/validation' ;
7+
58const TENANT_COOKIE_NAME = 'x-tenant-origin' ;
9+ const schema : ValidationSchema =
10+ {
11+ origin :
12+ {
13+ message : 'Invalid origin' ,
14+ URL :
15+ {
16+ required : true
17+ }
18+ }
19+ } ;
620
721export default class OriginMiddleware implements Middleware
822{
@@ -19,18 +33,16 @@ export default class OriginMiddleware implements Middleware
1933 origin = this . #getOriginFromHeader( request ) ;
2034 }
2135
22- if ( origin === undefined )
23- {
24- throw new BadRequest ( 'Missing origin' ) ;
25- }
36+ this . #validateOriginValue( origin ) ;
2637
27- request . setHeader ( 'origin' , origin ) ;
38+ // The origin header is validated and set here for use in other middlewares
39+ request . setHeader ( 'origin' , origin as string ) ;
2840
2941 const response = await next ( ) ;
3042
3143 if ( fromCookie === false )
3244 {
33- this . #setOriginCookie( response , origin ) ;
45+ this . #setOriginCookie( response , origin as string ) ;
3446 }
3547
3648 return response ;
@@ -50,17 +62,27 @@ export default class OriginMiddleware implements Middleware
5062 return ;
5163 }
5264
53- for ( const cookie of header . split ( '; ' ) )
65+ for ( const cookie of header . split ( ';' ) )
5466 {
5567 const [ key , value ] = cookie . split ( '=' ) ;
5668
57- if ( key === TENANT_COOKIE_NAME )
69+ if ( key . trim ( ) === TENANT_COOKIE_NAME )
5870 {
59- return value ;
71+ return value ?. trim ( ) ;
6072 }
6173 }
6274 }
6375
76+ #validateOriginValue( value : string | undefined ) : void
77+ {
78+ const result = validator . validate ( { url : value } , schema ) ;
79+
80+ if ( result . invalid )
81+ {
82+ throw new BadRequest ( 'Invalid origin' ) ;
83+ }
84+ }
85+
6486 #setOriginCookie( response : Response , origin : string ) : void
6587 {
6688 response . setHeader ( 'Set-Cookie' , `${ TENANT_COOKIE_NAME } =${ origin } ; Path=/; HttpOnly=true; SameSite=Strict; Secure` ) ;
0 commit comments