diff --git a/cmd/root.go b/cmd/root.go index c7c6a11..c639323 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -85,6 +85,7 @@ func init() { rootCmd.Flags().StringVarP(&config.HTTPListen, "listen", "l", config.HTTPListen, "HTTP bind interface and port for UI") rootCmd.Flags().IntVarP(&config.MaxMessages, "max", "m", config.MaxMessages, "Max number of messages to store") rootCmd.Flags().StringVar(&config.Webroot, "webroot", config.Webroot, "Set the webroot for web UI & API") + rootCmd.Flags().StringVar(&server.AccessControlAllowOrigin, "api-cors", server.AccessControlAllowOrigin, "Set API CORS Access-Control-Allow-Origin header") rootCmd.Flags().BoolVar(&config.UseMessageDates, "use-message-dates", config.UseMessageDates, "Use message dates as the received dates") rootCmd.Flags().StringVar(&config.UIAuthFile, "ui-auth-file", config.UIAuthFile, "A password file for web UI authentication") @@ -190,9 +191,13 @@ func initConfigFromEnv() { config.SMTPRelayAllIncoming = true } + // Misc options if len(os.Getenv("MP_WEBROOT")) > 0 { config.Webroot = os.Getenv("MP_WEBROOT") } + if len(os.Getenv("MP_API_CORS")) > 0 { + server.AccessControlAllowOrigin = os.Getenv("MP_API_CORS") + } if getEnabledFromEnv("MP_USE_MESSAGE_DATES") { config.UseMessageDates = true } diff --git a/server/server.go b/server/server.go index a5e23ce..8c7cb26 100644 --- a/server/server.go +++ b/server/server.go @@ -22,6 +22,9 @@ import ( //go:embed ui var embeddedFS embed.FS +// AccessControlAllowOrigin CORS policy +var AccessControlAllowOrigin string + // Listen will start the httpd func Listen() { isReady := &atomic.Value{} @@ -116,6 +119,10 @@ func middleWareFunc(fn http.HandlerFunc) http.HandlerFunc { w.Header().Set("Referrer-Policy", "no-referrer") w.Header().Set("Content-Security-Policy", config.ContentSecurityPolicy) + if AccessControlAllowOrigin != "" && strings.HasPrefix(r.RequestURI, config.Webroot+"api/") { + w.Header().Set("Access-Control-Allow-Origin", AccessControlAllowOrigin) + } + if config.UIAuthFile != "" { user, pass, ok := r.BasicAuth() @@ -149,6 +156,10 @@ func middlewareHandler(h http.Handler) http.Handler { w.Header().Set("Referrer-Policy", "no-referrer") w.Header().Set("Content-Security-Policy", config.ContentSecurityPolicy) + if AccessControlAllowOrigin != "" && strings.HasPrefix(r.RequestURI, config.Webroot+"api/") { + w.Header().Set("Access-Control-Allow-Origin", AccessControlAllowOrigin) + } + if config.UIAuthFile != "" { user, pass, ok := r.BasicAuth()