import { IncomingMessage , ServerResponse } from 'http' ; import isHTTPS from 'is-https' ; const defaults = { trustProxy : true , redirectPort : 443 , redirectHost : '' , redirectUnknown : true , enabled : true , statusCode : 307 , exclude : [ ] } ; type Options = Partial < typeof defaults > ; interface Middleware { ( req , res , next ? ) : void ; create : ( options : Options ) => Middleware ; } const isExcluded = ( url , patterns = [ ] ) => patterns . some ( pattern => url . match ( pattern ) ) ; function create ( _options ? ) { const options = { ... defaults , ... _options } ; const _port = options . redirectPort === 443 ? '' : ( ':' + options . redirectPort ) ; function redirectSSL ( req , res , next ? ) { const url = req . url || '' ; if ( ! options . enabled || isExcluded ( url , options . exclude ) ) { return next && next ( ) ; } const _isHttps = isHTTPS ( req , options . trustProxy ) ; const shouldRedirect = options . redirectUnknown ? ! _isHttps : _isHttps === false ; if ( shouldRedirect ) { const _redirectHost = ( options . redirectHost || req . headers . host || '' ) . split ( ':' ) [ 0 ] ; const _redirectURL = 'https://' + _redirectHost + _port + url ; res . writeHead ( options . statusCode , { Location : _redirectURL } ) ; return res . end ( _redirectURL ) ; } return next && next ( ) ; } redirectSSL . create = create ; return redirectSSL ; } export default create ( { } ) ;